我有很多要求。如何为所有请求设置默认标题?请给我例子
现在,我的代码如下所示:
HttpPost request = new HttpPost(url);
StringEntity params = null;
try {
params = new StringEntity(o.writeValueAsString(auth));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.addHeader("content-type", "application/json");
request.setEntity(params);
try {
client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
所以我有很多这样的要求
最佳答案
由于您正在使用HttpClientBuilder
,为什么不尝试使用其setDefaultHeaders()方法?
HttpClientBuilder client = HttpClientBuilder.create();
Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
client.setDefaultHeaders(header);
HttpPost request = new HttpPost(url);
StringEntity params = null;
try {
params = new StringEntity(o.writeValueAsString(auth));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.setEntity(params);
try {
client.build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
希望有帮助!
关于java - 如何为所有请求设置默认标题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48424966/