简体   繁体   中英

How can I send a JSON request using Jetty API Client?

I'm trying to send a JSON string to a Server using Jetty HttpClient, but I didn't found any good example about how can I do that, only request where the client send simple params by POST.

I manage to send the request using Apache HttpClient, but then I 've issues to keep the session when I perform the next request.

// rpcString is a json like  {"method":"Login","params":["user","passw"],"id":"1"}:
entity = new StringEntity(rpcString, HTTP.UTF_8);
HttpPost httpPost = new HttpPost("http://site.com:8080/json/users");
entity.setContentType("application/json");
httpPost.setEntity(entity);
client = HttpClientBuilder.create().build();
CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpPost);

If is possible, I like to do the same using jetty API client.

Thanks.

This question is really old, but I came accross with the same problem and this is how I solved it:

        // Response handling with default 2MB buffer
        BufferingResponseListener bufListener = new BufferingResponseListener() {
        @Override
        public void onComplete(Result result) {

            if (result.isSucceeded()) {
                // Do your stuff here
            }

        }
    };        

    Request request = httpClient.POST(url);
    // Add needed headers
    request.header(HttpHeader.ACCEPT, "application/json");
    request.header(HttpHeader.CONTENT_TYPE, "application/json");

    // Set request body
    request.content(new StringContentProvider(JSON_STRING_HERE), "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(bufListener);

To preserve the session with Apache HttpClient , you need to create the HttpClient instance once and then reuse it for all requests.

I don't know how the Jetty HTTP client API works but in general, you just need to build a POST request and add the JSON data encoded as an UTF-8 bytes as the request content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM