【一】、封裝HttpClient和Json解析
阿新 • • 發佈:2019-01-07
封裝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.目前為止整個工程的目錄如下:
這裡為了日後擴充套件,使用了介面的思想,需要解析不同格式的字串時,只需要在方法中傳入解析介面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上面給出:
主要程式碼如下:
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;
}
}