I am using the jersey client to send POST requests to a web server. I have generally been building up a Form object with key-value pairs. However, I now have to send a List within my request. Here's an abridged version of my code
// Phone is a POJO consisting of a few Strings
public void request(List<Phone> phones) {
Form form = new Form();
form.add("phones", phones);
ClientResponse response = WebService.getResponseFromServer(form);
String output = response.getEntity(String.class);
System.out.println(output);
}
public static ClientResponse getResponseFromServer(Form form) {
Client client = createClient();
WebResource webResource = client.resource(PATH);
return webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
}
Unfortunately, this doesn't seem to work, and I get a 400 bad request error. When I send a request directly
{"phones":[{"areaCode":"217","countryCode":"01","number":"3812565"}]}
I have no problems. Thanks in advance!
Given your example, based on typical POJO serialization, what you need isn't List<Phone>
but a class with a member phones
of a type List<Phone>
, otherwise the payload will look like this:
[{"areaCode":"217","countryCode":"01","number":"3812565"}]
So first, what you need is a jersey client with JSON serialization feature. You need to include jersey-json
(along with the jersey-client
) in your dependencies. Example in Maven:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.19</version>
</dependency>
Create your client like this:
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
Assuming you have a variable phones
which is the POJO, you can call this:
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, phones);
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.