封装HttpClient和Json解析(这里主要介绍封装的思想,具体的代码实现我会在github中给出)

在实际开发中,我们可能需要调用第三方服务器的接口,这就要使用到HttpClient来发送请求,这里就基于HttpClient封装了比较方便的助手类,并且扩展封装了响应信息的格式化(目前只支持Json格式化,开发者可以自定义格式化方法)

1.首先引入相关的依赖包:

<!--https://mvnrepository.com/artifact/com.alibaba/fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.29</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>

2.目前为止整个工程的目录如下:

【一】、封装HttpClient和Json解析_apache

这里为了日后扩展,使用了接口的思想,需要解析不同格式的字符串时,只需要在方法中传入解析接口ResponseParser的实现类,自定义具体的解析算法即可,并不需要在原来的代码上修改。

使用方法也很简单,调用的代码如下:

public void testPostRawData2Str() {
Map<String, Object> reqParams = new HashMap<>();
reqParams.put("id", UUID.randomUUID().toString());

Map<String, Object> res = HttpClientHelper.postRawData(url, reqParams);
System.out.println(res);
}

最终返回的是一个map集合的结果。

源代码我也在github上面给出:

​https://github.com/wulongtao/web-base-master/tree/master/src/main/java/com/xxh/web/util/http​

​https://github.com/wulongtao/web-base-master/tree/master/src/main/java/com/xxh/web/util/format​

主要代码如下:

package com.xxh.web.util.http;

import com.alibaba.fastjson.JSONObject;
import com.xxh.web.util.format.JsonResponseParser;
import com.xxh.web.util.format.ResponseParser;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
* HttpClient助手类,主要实现了请求响应数据的格式化,方便开发调用
* Created by wulongtao on 2017/5/15.
*/
public class HttpClientHelper {
private static final Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
private static ResponseParser responseParser = new JsonResponseParser();

/**
* 以rawData形式发送http post请求,Map集合方式返回
* @param url url
* @param reqParams 请求参数
* @return
*/
public static Map<String, Object> postRawData(String url, Map<String, Object> reqParams) {
String resp = postRawData2Str(url, reqParams);
return responseParser.parse(resp);
}

/**
* * 以rawData形式发送http post请求,Map集合方式返回
* @param url url
* @param reqParams 请求参数
* @param responseParser ResponseParser的实现类,实现parse方法
* @return
*/
public static Map<String, Object> postRawData(String url, Map<String, Object> reqParams, ResponseParser responseParser) {
String resp = postRawData2Str(url, reqParams);
return responseParser.parse(resp);
}

/**
* 以rawData形式发送http post请求,字符串形式返回响应结果
* @param url url
* @param reqParams 请求参数
* @return
*/
public static String postRawData2Str(String url, Map<String, Object> reqParams) {
String resp = "";

StringEntity entityStr = new StringEntity(JSONObject.toJSONString(reqParams), ContentType
.create("text/plain", "UTF-8"));

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entityStr);
CloseableHttpResponse response = null;

try {
response = httpClient.execute(httpPost);

//logger
logger.info("Do post raw data,status line=" + response.getStatusLine());


HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

if (resp == null || resp.equals("")) {
return "";
}

return resp;
}
}
package com.xxh.web.util.format;

import java.util.Map;

/**
* Created by wulongtao on 2017/5/16.
*/
public interface ResponseParser {
/**
* 解析http响应消息,可以扩展解析JSON、XML等格式
* @param resp
* @return
*/
Map<String, Object> parse(String resp);
}
package com.xxh.web.util.format;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.*;

/**
* Created by wulongtao on 2017/5/16.
*/
public class JsonResponseParser implements ResponseParser {

@Override
public Map<String, Object> parse(String resp) {
JSONObject jsonObject = JSONObject.parseObject(resp);
return parseFromJson(jsonObject);
}

/**
* 根据JSONObject对象解析成Map对象
* @param jsonObject
* @return
*/
private Map<String, Object> parseFromJson(JSONObject jsonObject) {
Map<String, Object> mRes = new HashMap<>();
Iterator<Map.Entry<String, Object>> it = jsonObject.entrySet().iterator();

while (it.hasNext()) {
Map.Entry<String, Object> param = it.next();

if (param.getValue() instanceof JSONObject) {
mRes.put(param.getKey(), parseFromJson((JSONObject) param.getValue()));
} else if (param.getValue() instanceof JSONArray) {
mRes.put(param.getKey(), json2List(param.getValue()));
} else {
mRes.put(param.getKey(), param.getValue());
}
}
return mRes;
}

private List<Map<String, Object>> json2List(Object json) {
JSONArray arrJson = (JSONArray) json;

List<Map<String, Object>> lst = new ArrayList<>();
for (int i = 0; i < arrJson.size(); i++) {

lst.add(parseFromJson(arrJson.getJSONObject(i)));
}

return lst;
}
}