lkallas
lkallas

Reputation: 1406

How to POST json as request body with Jetty http client?

I'm stuck with adding JSON to POST request body. There just isn't any method that sets the body of the request.

Is there any way I can achieve this. Otherwise I have to drop using Jetty.

This is how I make my POST request:

Request request = httpClient.POST(url);
        //request.method(HttpMethod.POST);
        request.header(HttpHeader.ACCEPT, "application/json");
        request.header(HttpHeader.CONTENT_TYPE, "application/json");

        // Add basic auth header if credentials provided
        if (isCredsAvailable()) {
            String authString = username + ":" + password;
            byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
            String authStringEnc = "Basic " + new String(authEncBytes);
            request.header(HttpHeader.AUTHORIZATION, authStringEnc);
        }

        request(send);

Any help is appreciated!

Upvotes: 5

Views: 13673

Answers (2)

许宗晖
许宗晖

Reputation: 1

thanks you solve the problem which puzzles me for a long time.

/*配置sslcontextfactory处理https请求*/
        SslContextFactory sslContextFactory = new SslContextFactory();
        HttpClient httpClient = new HttpClient(sslContextFactory);
        httpClient.setFollowRedirects(false);
        httpClient.start();

        /*配置post请求的url、body、以及请求头*/
        Request request =  httpClient.POST("https://a1.easemob.com/yinshenxia/yinshenxia/users");
        request.header(HttpHeader.CONTENT_TYPE, "application/json");
        request.content(new StringContentProvider("{\"username\":\"jliu\",\"password\":\"123456\"}","utf-8"));
//      request.param("username", "jliu");
//      request.param("password", "123456");
        ContentResponse response = request.send();
        String res = new String(response.getContent());
        System.out.println(res);
        httpClient.stop();

Upvotes: -2

lkallas
lkallas

Reputation: 1406

I was able to figure it out myself. The solution was staring at me the whole time.

Added one line and everything worked:

    // Set request body
    request.content(new StringContentProvider(JSON_HERE), "application/json");

Hope it will be helpful to others as well.

Upvotes: 8

Related Questions