泽西客户端异常:未找到消息正文编写器未找到、客户端、异常、泽西

2023-09-06 10:53:16 作者:北回归线上的约定

我正在使用 Jersey 客户端访问 PHP Web 服务以实现图像上传功能.我收到以下异常:

I am using Jersey client to hit a PHP web service for image uploading functionality. I am getting the following exception:

Caused by: com.sun.jersey.api.client.ClientHandlerException: 
A message body writer for Java type, class 
com.sun.jersey.multipart.FormDataMultiPart, and MIME media type, 
multipart/form-data, was not found
    at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
    ... 63 more

这是我正在使用的代码:

This is the code I am using:

WebResource webResource = Client.create().resource(HTTP_REST_URI);
JSONObject jSONObj = webResource.queryParams(queryParams)
      .type(MediaType.MULTIPART_FORM_DATA)
      .post(JSONObject.class, formDataMultiPart);

如何解决这个异常?

推荐答案

在创建Client时注册MultiPartWriter提供者:

ClientConfig cc = new DefaultClientConfig();
Client client;

cc.getClasses().add(MultiPartWriter.class);
client = Client.create(cc);

如果使用 Maven,这些是您在 pom.xml 中需要的依赖项:

If using Maven, these are the dependencies you need in your pom.xml:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>1.17.1</version>
</dependency>