简体   繁体   English

如何使用Jersey 2.26客户端与queryParam进行HTTP POST请求?

[英]How to do HTTP POST request with queryParam using Jersey 2.26 client?

I am using Jersey client to do requests. 我正在使用Jersey客户端进行请求。 Here is an example. 这是一个例子。

https://myschool.com/webapi/rest/student/submitJob?student={student:[{"id":1,"name":"Tom","age":20},{"id":2,"name":"Bob","age":20}]}&score={score:[{"id":1,"math":90,"art":80,"science":70},{"id":2,"math":70,"art":60,"science":80}]}

And the response would be like this: {"jobId":"123456789","jobStatus":"JobSubmitted"} 响应将是这样的:{“ jobId”:“ 123456789”,“ jobStatus”:“ JobSubmitted”}

This is my current code: 这是我当前的代码:

String student = {student:[{"id":1,"name":"Tom","age":20},{"id":2,"name":"Bob","age":20}]};
String score = {score:[{"id":1,"math":90,"art":80,"science":70},{"id":2,"math":70,"art":60,"science":80}]}

String responseResult = client.target("https://myschool.com/webapi/rest/student/").path("submitJob")
                        .queryParam("student", student).queryParam("score", score).request("application/json").get(String.class);

The problem is the real request URI is too long that I got 414 error. 问题是实际的请求URI太长,导致出现414错误。 So I need to use POST instead of GET method. 所以我需要使用POST而不是GET方法。 But I send the request using queryParam but not Body. 但是我使用queryParam而不是Body发送请求。 Could anyone tell me how to do that? 谁能告诉我该怎么做? Thanks. 谢谢。

Use POST Method and Set Content type as "application/x-www-form-urlencoded". POST method increases allowable url request limit.


 String student = {student:[{"id":1,"name":"Tom","age":20},{"id":2,"name":"Bob","age":20}]};
 String score = {score:[{"id":1,"math":90,"art":80,"science":70},{"id":2,"math":70,"art":60,"science":80}]};
 Client client = ClientBuilder.newClient();
 Form input = new Form();
 input.param("student", student);
 input.param("score", score);
 Entity<Form> entity = Entity.entity(input, MediaType.APPLICATION_FORM_URLENCODED);
 String url = "https://myschool.com/webapi/rest/student/submitJob";
 ClientResponse response = client.target.request(MediaType.APPLICATION_JSON_TYPE)
.post(entity);

This code is based on the inspiration from @MohammedAbdullah 's answer, as well as jersey documentation. 该代码基于@MohammedAbdullah的回答以及球衣文档。

Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://myschool.com/webapi/rest/student/").path("submitJob");
Form form = new Form();
form.param("student", student);
form.param("score", score);
String responseResult = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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