上篇文章介绍了插件式配置HttpClient,本文将介绍插件式配置Header。
为什么要配置header在前面已经提到了,还里再简单说一下,要使用HttpClient模拟请求,去访问各种接口或者网站资源,都有可能有各种限制,比如说java客户端模拟访问csdn博客,就必须设置User-Agent,否则就报错了。还有各种其他情况,必须的设置一些特定的Header,才能请求成功,或者才能不出问题。
好了就说这么多,本次还是采用构造者模式的级联调用方式,来完成该工具类。在该工具类中,为所有常用的Http Request Header都提供了设置方法。具体参数参考的链接是HTTP Header 详解。
不再多废话了,看具体代码吧:
package com.tgb.ccl.http.common;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
/**
* 创建HttpReqHead
*
* @author arron
* @date 2015年11月9日 上午10:37:23
* @version 1.0
*/
public class HttpHeader {
private HttpHeader() {};
public static HttpHeader custom() {
return new HttpHeader();
}
//记录head头信息
private Map<String, Header> headerMaps = new HashMap<String, Header>();
/**
* 指定客户端能够接收的内容类型
* 例如:Accept: text/plain, text/html
*
* @param accept
*/
public HttpHeader accept(String accept) {
headerMaps.put(HttpReqHead.ACCEPT,
new BasicHeader(HttpReqHead.ACCEPT, accept));
return this;
}
/**
* 浏览器可以接受的字符编码集
* 例如:Accept-Charset: iso-8859-5
*
* @param acceptCharset
*/
public HttpHeader acceptCharset(String acceptCharset) {
headerMaps.put(HttpReqHead.ACCEPT_CHARSET,
new BasicHeader(HttpReqHead.ACCEPT_CHARSET, acceptCharset));
return this;
}
/**
* 指定浏览器可以支持的web服务器返回内容压缩编码类型
* 例如:Accept-Encoding: compress, gzip
*
* @param acceptEncoding
*/
public HttpHeader acceptEncoding(String acceptEncoding) {
headerMaps.put(HttpReqHead.ACCEPT_ENCODING,
new BasicHeader(HttpReqHead.ACCEPT_ENCODING, acceptEncoding));
return this;
}
/**
* 浏览器可接受的语言
* 例如:Accept-Language: en,zh
*
* @param acceptLanguage
*/
public HttpHeader acceptLanguage(String acceptLanguage) {
headerMaps.put(HttpReqHead.ACCEPT_LANGUAGE,
new BasicHeader(HttpReqHead.ACCEPT_LANGUAGE, acceptLanguage));
return this;
}
/**
* 可以请求网页实体的一个或者多个子范围字段
* 例如:Accept-Ranges: bytes
*
* @param acceptRanges
*/
public HttpHeader acceptRanges(String acceptRanges) {
headerMaps.put(HttpReqHead.ACCEPT_RANGES,
new BasicHeader(HttpReqHead.ACCEPT_RANGES, acceptRanges));
return this;
}
/**
* HTTP授权的授权证书
* 例如:Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
*
* @param authorization
*/
public HttpHeader authorization(String authorization) {
headerMaps.put(HttpReqHead.AUTHORIZATION,
new BasicHeader(HttpReqHead.AUTHORIZATION, authorization));
return this;
}
/**
* 指定请求和响应遵循的缓存机制
* 例如:Cache-Control: no-cache
*
* @param cacheControl
*/
public HttpHeader cacheControl(String cacheControl) {
headerMaps.put(HttpReqHead.CACHE_CONTROL,
new BasicHeader(HttpReqHead.CACHE_CONTROL, cacheControl));
return this;
}
/**
* 表示是否需要持久连接(HTTP 1.1默认进行持久连接)
* 例如:Connection: close 短链接; Connection: keep-alive 长连接
*
* @param connection
* @return
*/
public HttpHeader connection(String connection) {
headerMaps.put(HttpReqHead.CONNECT