2012-05-21 26 views
3

我試圖調用與想法下面的客戶端代碼REST服務來發送一些字符串消息細節,以及附件文件:通過新澤西州和發送文件X WWW的形式,進行了urlencoded

ClientConfig config = new DefaultClientConfig(); 
config.getClasses().add(FormProvider.class); 
Client client = Client.create(config); 
WebResource webResource = client.resource("http://some.url/path1/path2"); 

File attachment = new File("./file.zip"); 

FormDataBodyPart fdp = new FormDataBodyPart(
      "content", 
      new ByteArrayInputStream(Base64.encode(FileUtils.readFileToByteArray(attachedLogs))), 
      MediaType.APPLICATION_OCTET_STREAM_TYPE); 
form.bodyPart(fdp); 

ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);  

我要定位的服務器接受Base64編碼的內容,所以這就是爲什麼從文件到ByteArray的額外傳輸。

此外,我發現類com.sun.jersey.core.impl.provider.entity.FormProvider與「x-www-form-urlencoded」請求的生產和消費相關。

@Produces({"application/x-www-form-urlencoded", "*/*"}) 
@Consumes({"application/x-www-form-urlencoded", "*/*"}) 

但我仍最終了以下堆棧跟蹤:

com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.sun.jersey.multipart.FormDataMultiPart, and MIME media type, application/x-www-form-urlencoded, was not found at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149) ~[jersey-client-1.9.1.jar:1.9.1] 
at com.sun.jersey.api.client.Client.handle(Client.java:648) ~[jersey-client-1.9.1.jar:1.9.1] 
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670) ~[jersey-client-1.9.1.jar:1.9.1] 
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74) ~[jersey-client-1.9.1.jar:1.9.1] 
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563) ~[jersey-client-1.9.1.jar:1.9.1] 

在這一個任何幫助嗎?

回答

4

我設法讓客戶端的東西工作。問題在於我強制將文件作爲單獨的郵件正文部分發送,而x-www-form-urlencoded is actually packing all of the data as parameters in the query that is the entire body

所以工作的客戶端代碼,如果你想通過澤西post方法發送附件是:

ClientConfig config = new DefaultClientConfig(); 
Client client = Client.create(config); 
WebResource webResource = client.resource("http://some.url/path1/path2"); 

MultivaluedMapImpl values = new MultivaluedMapImpl(); 
values.add("filename", "report.zip"); 
values.add("text", "Test message"); 
values.add("content", new String(Base64.encode(FileUtils.readFileToByteArray(attachedLogs)))); 
ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, values); 

的阿帕奇百科全書的Base64編碼器被要求在我的情況下,以轉換文件到編碼的字節數組,不知道如果這是一般要求。

+0

如果您正在上傳文件,使用multipart會更有效,但工作很好。如果你想嘗試多部分,請將你的接受設置爲「multipart/form-data」,然後使用客戶端的FormDataMultiPart爲你想發送的所有部分(文件,字段等)。 –

+0

注意:對於字段使用.field(「name」,「value」)。 –

1

嘗試使用Multipart/form-data而不是application/x-www-form-urlencodedThis tutorial可能會有所幫助。

+0

謝謝亞歷克斯,但我無法控制服務器端的情況下,所以切換到multipart不是一個選項。 –

相關問題