[英]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. 我正在尝试使用Jetty HttpClient将JSON字符串发送到服务器,但是我没有找到任何有关如何执行此操作的好示例,仅请求客户端通过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. 我设法使用Apache HttpClient发送请求,但是当我执行下一个请求时,我不得不保留会话。
// 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. 如果可能,我喜欢使用Jetty API客户端执行相同的操作。
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. 要保留与Apache HttpClient的会话,您需要创建一次
HttpClient
实例,然后将其重新用于所有请求。
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. 我不知道Jetty HTTP客户端API的工作方式,但是通常,您只需要构建一个POST请求并添加编码为UTF-8字节的JSON数据作为请求内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.