【发布时间】:2014-10-01 20:15:36
【问题描述】:
我们正在使用 Jersey 1.18 使用 REST API。我们希望使用 Jakarta Commons HttpClient 3.1 作为后端,同时使用 REST API。因此,我们使用 ApacheHttpClientHandler 从 HttpClient 获取 Jersey Client 的对象。 它适用于 GET 请求。但是,当我们调用 POST 请求时,我们会得到 NullPointer 异常。以下是带有错误消息的代码摘录:
/*使用 ApacheHttpClientHandler 引发 NPE 的 POST 调用代码 */
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.client.apache.ApacheHttpClientHandler;
HttpClient httpClient = new HttpClient();
ApacheHttpClientHandler clientHandler = new ApacheHttpClientHandler(httpClient);
String url = "http://petstore.swagger.wordnik.com:80/api/store/order";
WebResource.Builder builder = new Client(clientHandler).resource(url).accept("application/json").entity("{}", "application/json");
ClientResponse clientResponse = null;
try {
clientResponse = builder.post(ClientResponse.class);
} finally {
if (clientResponse != null) {
clientResponse.close();
}
}
System.out.println("Status: " + clientResponse.getStatus());
我们收到的错误:
Exception in thread "main" java.lang.NullPointerException code
at com.sun.jersey.api.client.RequestWriter$RequestEntityWriterImpl.<init>(RequestWriter.java:186)
at com.sun.jersey.api.client.RequestWriter.getRequestEntityWriter(RequestWriter.java:248)
at com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.executeMethod(DefaultApacheHttpMethodExecutor.java:121)
at com.sun.jersey.client.apache.ApacheHttpClientHandler.handle(ApacheHttpClientHandler.java:175)
at com.sun.jersey.api.client.Client.handle(Client.java:652)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:560)
如果我们将客户端创建从 new Client(clientHandler) 更改为 new Client(),那么我们会得到预期的响应 200。
类路径中的 jar 文件
- commons-httpclient-3.1.jar
- jersey-client-1.18.jar
- jersey-apache-client-1.18.jar
- commons-logging-1.0.4.jar
- jersey-core-1.18.jar
- commons-codec-1.2.jar
有没有人遇到过类似的问题并且知道这个问题的解决方法?
【问题讨论】:
-
在 Mozilla 中使用 REST 客户端或任何其他客户端(如用于 POST 的 SOAP UI)进行首次测试,并检查结果是否出现。
-
当通过 Mozilla 中的任何 REST 客户端调用 API 时,甚至使用没有 ApacheClientHandler 的 jersey 客户端调用时,API 都可以正常工作。问题仅在于我们将 ApacheClientHandler 与 Jersey 客户端一起使用时
标签: java rest apache-commons-httpclient jersey-client