在Java方法中,我想使用Jersey客戶端對象在REST風格的Web服務(也使用Jersey編寫)上執行POST操作,但不知道如何使用客戶端發送將在服務器上用作FormParam的值。我能夠發送查詢參數就好了。使用Jersey客戶端執行POST操作
在此先感謝。
在Java方法中,我想使用Jersey客戶端對象在REST風格的Web服務(也使用Jersey編寫)上執行POST操作,但不知道如何使用客戶端發送將在服務器上用作FormParam的值。我能夠發送查詢參數就好了。使用Jersey客戶端執行POST操作
在此先感謝。
我自己還沒有做過這件事,但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);
那任何幫助嗎?
你也可以試試這個:如果你需要做一個文件上傳
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();
,你需要使用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);
從澤西島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"
的格式發送。
最簡單的:
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);
現在在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);
鏈接POST請求,現在是可操作的 – orique 2013-12-11 12:29:20