我使用 jersey-client 来使用 REST 服务。 我需要请求的实体和 Last-Modified header 。
所以我做了以下事情:
ClientResponse response = webResource.get(ClientResponse.class);
Person person = response.getEntity(Person.class);
行得通。我得到一个响应,我可以将实体(即 XML)编码到我的 POJO 中。 当我调试并查看响应的 header 时,我看到有一个 Last-Modified header 集。
但是当我尝试通过
检索日期时response.getLastModified();
我在 URLConnectionClientHandler 的某个地方得到了一个 NPE。
有人知道我做错了什么吗?
编辑:根据跟踪的要求
java.lang.NullPointerException: null
at com.sun.jersey.api.client.ClientResponse.getLastModified(ClientResponse.java:647) ~[jersey-client-1.12.jar:1.12]
at a.o.u.user.dao.impl.uds.PersonenUdsClient.getPerson(PersonenUdsClient.java:103) ~[um-user-2.5.0-Beta1-SNAPSHOT.jar:na]
at a.o.u.user.dao.impl.UserDaoUdsImpl.mergeWithUdsUser(UserDaoUdsImpl.java:282) ~[um-user-2.5.0-Beta1-SNAPSHOT.jar:na]
at a.o.u.user.dao.impl.UserDaoUdsImpl.getUserWithEmail(UserDaoUdsImpl.java:124) ~[um-user-2.5.0-Beta1-SNAPSHOT.jar:na]
at ...
编辑: 按照 npe 的建议,我深入研究了代码。我想我发现了问题。除了 jersey-client,我在类路径中也有 cxf。 jersey 和 cxf 都提供了一个名为 RuntimeDelegateImpl 的类。但是 CXFs 版本没有 DateHeaderDelegate。我认为使用了错误的 RuntimeDelegateImpl 版本 (CXF)。
到目前为止,我还没有找到如何明确设置要使用的 RuntimeDelegateImpl。
最佳答案
ClientResponse#getLastModified()
1.12 版的实现如下所示:
/*639*/ /**
/*640*/ * Get the last modified date.
/*641*/ *
/*642*/ * @return the last modified date, otherwise <code>null</code> if not present.
/*643*/ */
/*644*/ public Date getLastModified() {
/*645*/ String d = getHeaders().getFirst("Last-Modified");
/*646*/
/*647*/ return (d != null) ? dateDelegate.fromString(d) : null;
/*648*/ }
您在第 647 行遇到了一个 NullPointerException
,因此看起来 dateDelegate
是 null
。现在,dateDelegate
对象在第 321 行被初始化,如下所示:
/*321*/ protected static final HeaderDelegate<Date> dateDelegate =
/*322*/ RuntimeDelegate.getInstance().createHeaderDelegate(Date.class);
现在,该字段是 final
,因此在此初始化后不能更改 - 这意味着 dateDelegate
从一开始就是 null
- 并且这意味着,您遇到了某种配置问题,并且未创建委托(delegate)。
此外,委托(delegate)是在 AbstractRuntimeDelegate
类 ( source for 1.12 here ) 中创建的,如下所示:
/* 88*/ map.put(Date.class, _createHeaderDelegate(Date.class));
这个兔子洞越陷越深,所以我要到此为止了,但你知道怎么走。
最后但同样重要的是 - 调试器是你的 friend ,我的 friend ;-)
关于java - Jersey 客户端在 ClientResponse.getLastModified() 中抛出 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11133844/