2010-01-25 63 views
47

在Java方法中,我想使用Jersey客戶端對象在REST風格的Web服務(也使用Jersey編寫)上執行POST操作,但不知道如何使用客戶端發送將在服務器上用作FormParam的值。我能夠發送查詢參數就好了。使用Jersey客戶端執行POST操作

在此先感謝。

回答

70

我自己還沒有做過這件事,但Google-Fu的一小段內容揭示了一個tech tip on blogs.oracle.com,其中包含您要求的具體示例。

例如,從博客文章採取:

MultivaluedMap formData = new MultivaluedMapImpl(); 
formData.add("name1", "val1"); 
formData.add("name2", "val2"); 
ClientResponse response = webResource 
    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) 
    .post(ClientResponse.class, formData); 

那任何幫助嗎?

+2

鏈接POST請求,現在是可操作的 – orique 2013-12-11 12:29:20

2

你也可以試試這個:如果你需要做一個文件上傳

MultivaluedMap formData = new MultivaluedMapImpl(); 
formData.add("name1", "val1"); 
formData.add("name2", "val2"); 
webResource.path("yourJerseysPathPost").queryParams(formData).post(); 
3

,你需要使用MediaType.MULTIPART_FORM_DATA_TYPE。 看起來像MultivaluedMap不能用於這個,所以這是一個FormDataMultiPart的解決方案。

InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload); 

FormDataMultiPart part = new FormDataMultiPart(); 
part.field("String_key", "String_value"); 
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE); 
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part); 
33

從澤西島2.X開始,MultivaluedMapImpl類由MultivaluedHashMap取代。你可以用它來添加表單數據並將數據發送到服務器:

WebTarget webTarget = client.target("http://www.example.com/some/resource"); 
    MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>(); 
    formData.add("key1", "value1"); 
    formData.add("key2", "value2"); 
    Response response = webTarget.request().post(Entity.form(formData)); 

注意窗體實體在"application/x-www-form-urlencoded"的格式發送。

2

最簡單的:

Form form = new Form(); 
form.add("id", "1");  
form.add("name", "supercobra"); 
ClientResponse response = webResource 
    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) 
    .post(ClientResponse.class, form); 
12

現在在Jersey Client documentation

實施例5.1第一例子。與表單參數

Client client = ClientBuilder.newClient(); 
WebTarget target = client.target("http://localhost:9998").path("resource"); 

Form form = new Form(); 
form.param("x", "foo"); 
form.param("y", "bar"); 

MyJAXBBean bean = 
target.request(MediaType.APPLICATION_JSON_TYPE) 
    .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE), 
     MyJAXBBean.class); 
+0

不Jersey客戶端自動轉換返回類型爲'MyJAXBBean.class'?如何實現這一目標? – DerekY 2015-06-30 02:58:06

+0

調用鏈的最後一個參數是一個類,告訴Jersey將響應內容映射到MyJAXBBean對象。你也可以將它映射到一個字符串,並用你自己選擇的工具反序列化它。 – otonglet 2015-06-30 15:30:41

相關問題