我希望能够动态设置标头。这条线对我有用:
WebResource webResource = client.resource(doSomethingURL);
webResource
.header("test1", test1)
.post(ClientResponse.class, postData);
但是在编写动态头文件时,它会使代码变得不必要。我想做点什么:
WebResource webResource = client.resource(doSomethingURL);
if(a>b){
webResource.header("test1",test1);
}else{
webResource.header("test2",test2);
}
webResource.post(ClientResponse.class, postData);
我尝试了这个,但由于某种原因它会抛出错误:
ClientResponse response = getWebResource(URI + "something").post(ClientResponse.class, DataForPost);
public WebResource getWebResource(String url){
WebResource webResource = client.resource(url);
webResource
.header("test1", test1);
return webResource;
}
我得到的错误是:
java.lang.ClassCastException:java.lang.Class无法强制转换为com.sun.jersey.api.client.ClientResponse
答案 0 :(得分:0)
我用构建器想出来了。如果有任何人遇到同样的问题,这可能有所帮助:
WebResource webResource = client.resource(doSomethingURL);
//Use builder object
WebResource.Builder builder = webResource.getRequestBuilder();
if(condition){
builder = builder.header("test1", "test1String")
.header("test2", "test2String"); // this way you can add multiple headers.
}else{
builder = builder.header("test3", "test3String");
}
builder.post(ClientResponse.class, postData);