[英]Jersey Client - How to send List in a form with a POST request
我正在使用jersey客戶端將POST請求發送到Web服務器。 通常,我一直在構建具有鍵-值對的Form對象。 但是,我現在必須在請求中發送一個列表 。 這是我的代碼的精簡版
// 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);
}
不幸的是,這似乎不起作用,並且我收到一個400錯誤的請求錯誤。 當我直接發送請求時
{"phones":[{"areaCode":"217","countryCode":"01","number":"3812565"}]}
我沒問題 提前致謝!
對於您的示例,基於典型的POJO序列化,您需要的不是List<Phone>
而是一個成員phones
類型為List<Phone>
,否則有效負載將如下所示:
[{"areaCode":"217","countryCode":"01","number":"3812565"}]
因此,首先,您需要的是帶有JSON序列化功能的jersey客戶端。 您需要在依賴項中包含jersey-json
(以及jersey-client
)。 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>
像這樣創建您的客戶:
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
假設您有一個可變phones
,即POJO,則可以這樣稱呼:
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, phones);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.