[英]How to POST json as request body with Jetty http client?
I'm stuck with adding JSON to POST request body. 我坚持将JSON添加到POST请求正文中。 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.
否则,我必须放弃使用Jetty。
This is how I make my POST request: 这是我发出POST请求的方式:
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! 任何帮助表示赞赏!
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. 希望对其他人也有帮助。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.