如何为所有请求设置默认标头?

时间:2018-01-24 14:34:17

标签: java apache-httpclient-4.x

我有很多要求。如何为所有请求设置默认标头?请给我举个例子

现在我的代码看起来像这样:

    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();
    }

所以我有很多这样的要求

2 个答案:

答案 0 :(得分:2)

由于您使用的是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();
}

希望有所帮助!

答案 1 :(得分:0)

最尴尬的是尝试捕获。最好将它们扔给调用者,并依赖于那里的日志记录。

然而,一次尝试也是可能的。样式try { declaration + assigning + processing最好是HttpPost request = new HttpPost(url); request.addHeader("content-type", "application/json"); try { request.setEntity(new StringEntity(o.writeValueAsString(auth))); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); } catch (IOException e) { Logger.log(Level.SEVERE, e); } }

然后一个人已经变得更短,更易读。

top: auto

HttpClient部分仍然有点可疑,可以在没有声明的情况下进行缩减。

存在替代方案,例如使用注释,Spring和一些更多的声明性技术。但这还不够短。