![](/img/trans.png)
[英]How can I send request to the server with JSON data and fileupload from AngularJS client using $resource via JAX-RS(Jersey)?
[英]How can I send a JSON request using Jetty API Client?
我正在尝试使用Jetty HttpClient将JSON字符串发送到服务器,但是我没有找到任何有关如何执行此操作的好示例,仅请求客户端通过POST发送简单参数。
我设法使用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);
如果可能,我喜欢使用Jetty API客户端执行相同的操作。
谢谢。
这个问题确实很老,但是我遇到了同样的问题,这就是我解决的方法:
// 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);
要保留与Apache HttpClient的会话,您需要创建一次 HttpClient
实例,然后将其重新用于所有请求。
我不知道Jetty HTTP客户端API的工作方式,但是通常,您只需要构建一个POST请求并添加编码为UTF-8字节的JSON数据作为请求内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.