Apache的HttpClient的使用

Apache的HttpClient可以被用于从客户端发送HTTP请求到服务器端,其中封装了客户端发送http的get和post请求

使用Apache的HttpClient发送GET和POST请求的步骤如下:

1. 使用帮助类HttpClients创建CloseableHttpClient对象.

2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.

3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.

4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.

5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例

6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.

7. 最后关闭HttpClient资源.

private List<String> splitQueryString(String queryString)

throws UnsupportedEncodingException, IOException,

ClientProtocolException {

List<String> analyzeKeywords = new ArrayList<String>();

// 2016年1月5日 获得拆分的词

//从客户端发送HTTP请求到服务器端,

CloseableHttpClient httpClient = HttpClients.createDefault();

// 用get方法发送http请求

// ik_max_word: 会将文本做最细粒度的拆分,比如会将“中华人民共和国国歌”拆分为“中华人民共和国,中华人民,中华,华人,人民共和国,人民,人,民,共和国,共和,和,国国,国歌”,会穷尽各种可能的组合;

// ik_smart: 会做最粗粒度的拆分,比如会将“中华人民共和国国歌”拆分为“中华人民共和国,国歌”。

Map<String, Object> analyzerMap = commonService.getConfigurationInfoByKey(Constant.ANALYZER);

int analyzerType = StringUtil.nullToInteger(analyzerMap.get("config_value"));

String analyzer = "";

if(analyzerType==0){

analyzer = "ik_max_word";

}else{

analyzer = "ik_smart";

}

HttpGet get = new HttpGet(

Constant.SEARCH_URL

+ "/appkeyword/_analyze?analyzer="+analyzer+"&pretty=true&text="

+ URLEncoder.encode(queryString, "utf-8"));

CloseableHttpResponse httpResponse = null;

// 发送get请求

httpResponse = httpClient.execute(get, credentialContext);

try {

// response实体

HttpEntity entity = httpResponse.getEntity();

if (null != entity) {

if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

String response = EntityUtils.toString(entity,

"utf8");

JSONObject resObject = JSON.parseObject(response);

JSONArray tokens = resObject.getJSONArray("tokens");

if (tokens.size() > 0) {

for (int i = 0; i < tokens.size(); i++) {

JSONObject token = (JSONObject) tokens

.get(i);

if (StringUtil.isNotEmpty(token

.getString("token"))) {

analyzeKeywords.add(token

.getString("token"));

}

}

}

}

}

} finally {

httpResponse.close();

}

return analyzeKeywords;

}