我正在使用Jax-RS 2.0(Resteasy 3.0.7.Final)实现Restful服务,并共享客户端和服务之间的接口。
返回值为void,因为不推荐使用ClientResponse,因为RestEasy在版本3 +中引入了JAX-RS 2.0。
要返回新创建对象的位置,请使用@Context
注释注入响应,然后添加Content-Location标头。
例如:
共享界面:
@Path("/")
@Consumes("application/xml")
@Produces("application/xml")
interface Resource {
@Path("createSomething")
void createSomething(AnyObject object);
...
}
实施班(服务):
class ResourceImpl {
...
@Context org.jboss.resteasy.spi.HttpResponse response;
...
@Override
void createSomething(AnyObject object) throws AnyException {
String id = service.create(object);
response.getOutputHeaders().putSingle("Content-Location",
"/createSomething/" + id);
response.setStatus(Response.Status.CREATED.getStatusCode());
}
}
客户端(使用Resteasy Proxy Framework构建):
...
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(baseUrl);
Resource resource = (Resource) target.proxy(Resource.class);
resource.createSomething(anyObject);
...
如何检索已由服务注入的标头信息(以及其他类似Atom链接)?
使用客户端过滤器和拦截器是否合理?
谢谢
答案 0 :(得分:0)
我找到的最佳解决方案是使用Filter来处理传入的响应头。
public class HeaderFilter implements ClientResponseFilter {
private Map<String, String> headers = new HashMap<>();
private List<String> headerFilter = new ArrayList<>();
public final void addHeaderFilter(final String header) {
headerFilter.add(header);
}
public final void removeHeaderFilter(final String header) {
headerFilter.remove(header);
}
public final String getHeader(final String header) {
return headers.get(header);
}
@Override
public final void filter(final ClientRequestContext requestContext,
final ClientResponseContext responseContext)
throws IOException {
headers = new HashMap<>();
for (String headerToLookFor : headerFilter) {
String header = responseContext.getHeaderString(headerToLookFor);
if (header != null) {
headers.put(headerToLookFor, header);
} else {
...
}
}
}
}