我正在尝试使用以下客户端代码调用 REST 服务,以发送一些字符串消息详细信息以及附件文件:
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 编码的内容,这就是从 File 到 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]
对这个有帮助吗?