Adv*_*cer 1 java exception jax-rs jersey-client
我正在构建一个Rest Client
使用jersey-client 2.19
:
public ReleaseEntity createRelease(ReleaseEntity newRelease, int workspaceId) {
Releases wrapper = new Releases();
wrapper.setData(Arrays.asList(newRelease));
WebTarget target = client.target(urlPrefix)
.path(AgmUrls.getReleasesUrl(workspaceId));
wrapper = target
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(wrapper, MediaType.APPLICATION_JSON))
.readEntity(Releases.class);
return wrapper.getData().get(0);
}
Run Code Online (Sandbox Code Playgroud)
客户端在初始化 constructor
this.client = ClientBuilder.newClient();
Run Code Online (Sandbox Code Playgroud)
问题是,如果响应不好,post
调用不会抛出异常,也不会抛出explicit
异常runtime
。
我应该手动执行此操作,还是我遗漏了什么?
这个问题已经很过时了,但最好防止其他人重复同样的错误......
代替
result = target
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(input, MediaType.APPLICATION_JSON))
.readEntity(Releases.class);
Run Code Online (Sandbox Code Playgroud)
它post(entity)
返回一个被调用的Response
对象readEntity
,最好使用重载post(entity, responseType)
,这会抛出WebApplicationException
错误状态代码。
// throws runtime exception derived from WebApplicationException
// on error-statuscodes
result = target
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(input, MediaType.APPLICATION_JSON), Releases.class);
Run Code Online (Sandbox Code Playgroud)
JAX-RS 中的每个 http 方法都有这样的重载方法来读取响应或表示对象。强烈建议在任何情况下读取表示对象以消耗潜在的响应主体。
// consumes response as string and guarantees to close the http call.
// A no-arg delete(); would be a potential leak!
target.request().delete(String.class);
Run Code Online (Sandbox Code Playgroud)
不幸的是,当必须读取响应头时,仍然需要读取Response
而不是表示对象。
归档时间: |
|
查看次数: |
1666 次 |
最近记录: |