封裝HttpClient簡化呼叫第三方api
阿新 • • 發佈:2019-02-03
一:工具類
package com.jianlejun.util; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSONObject; /** * HttpClient操作類 * * @author allan */ public class ApiUtils { public static URI buildUri(String url, Map<Object, Object> paramMap) throws URISyntaxException { URIBuilder builder = new URIBuilder(url); if (paramMap != null && !paramMap.isEmpty()) { for (Entry<Object, Object> entry : paramMap.entrySet()) { if (entry.getValue() instanceof java.util.List) { List<Object> list = (List<Object>) entry.getValue(); List<NameValuePair> nvps = new ArrayList(); for (Object value : list) { nvps.add(new BasicNameValuePair(entry.getKey().toString(), value.toString())); } builder.setParameters(nvps); } else { builder.setParameter(entry.getKey().toString(), entry.getValue().toString()); } } } return builder.build(); } /** * * @param <T> * @param url 請求的apiUrl * @param paramMap ?a=b&c=d形式引數 * @param token 認證token * @param clazz 需要傳遞的json資料 * @return * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ public static <T> String postApi(String url, Map paramMap, String token, T clazz) throws URISyntaxException, ClientProtocolException, IOException { HttpPost post = new HttpPost(buildUri(url, paramMap)); if (token != null) { post.setHeader("Authorization", "Bearer " + token); } if (clazz != null) { StringEntity httpEntity = new StringEntity(JSONObject.toJSONString(clazz), "UTF-8"); httpEntity.setContentType("application/json;charset=UTF-8"); post.setEntity(httpEntity); } HttpResponse resp = createHttpClient().execute(post); String respData = EntityUtils.toString(resp.getEntity()); return respData == null ? "" : respData; } public static String getApi(String url, Map<Object, Object> paramMap, String token) throws URISyntaxException, ClientProtocolException, IOException { HttpGet get = new HttpGet(buildUri(url, paramMap)); if (token != null) { get.setHeader("Authorization", "Bearer " + token); } HttpResponse resp = createHttpClient().execute(get); String respData = EntityUtils.toString(resp.getEntity()); return respData == null ? "" : respData; } public static <T> String putApi(String url, Map paramMap, String token, T clazz) throws URISyntaxException, ClientProtocolException, IOException { HttpPut put = new HttpPut(buildUri(url, paramMap)); if (token != null) { put.setHeader("Authorization", "Bearer " + token); } if (clazz != null) { StringEntity httpEntity = new StringEntity(JSONObject.toJSONString(clazz), "UTF-8"); httpEntity.setContentType("application/json;charset=UTF-8"); put.setEntity(httpEntity); } HttpResponse resp = createHttpClient().execute(put); String respData = EntityUtils.toString(resp.getEntity()); return respData == null ? "" : respData; } public static HttpClient createHttpClient() { return HttpClients.createDefault(); } }
二:客戶端
package com.jianlejun.service; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSONObject; import com.jianlejun.common.util.DateUtil; import com.jianlejun.common.util.PropertyConfigurer; import com.jianlejun.dto.Constant; import com.jianlejun.request.AdjustDeskRequest; import com.jianlejun.request.GetStatusHistoryRequest; import com.jianlejun.request.GetTokenRequest; import com.jianlejun.util.ApiUtils; @Service public class Client { private static Logger LOG = LoggerFactory.getLogger(Client.class); private String baseApiUrl; private String uniqueName; private String password; // 直接賦值,僅供測試使用, public Client() { baseApiUrl = "http://jianlejun.xxx.cn"; uniqueName = "userName"; password = "password"; } public String getToken() throws ClientProtocolException, URISyntaxException, IOException { String respData = ApiUtils.postApi(baseApiUrl + Constant.DESK_API_URI.GET_TOKEN, null, null, new GetTokenRequest(uniqueName, password)); JSONObject obj = JSONObject.parseObject(respData); return obj.getString("data"); } //http://aa.bb.cn?aa=11&aa=22&aa=33 public String getStatus(List<String> ids) throws ClientProtocolException, URISyntaxException, IOException { Map paramMap = new HashMap(); if (ids == null || ids.isEmpty()) { paramMap = null; } else { paramMap.put("deskId", ids); } String respData = ApiUtils.getApi(baseApiUrl + Constant.DESK_API_URI.GET_STATUS, paramMap, this.getToken()); return respData; } public String getStatusHistory(GetStatusHistoryRequest req) throws ClientProtocolException, URISyntaxException, IOException, ParseException { Map paramMap = new HashMap(); if (req == null) { paramMap = null; } else { if (req.getDeskId() != null) { paramMap.put("deskId", req.getDeskId()); } if (req.getStartTime() != null) { paramMap.put("startTime", DateUtil.format(req.getStartTime())); } if (req.getEndTime() != null) { paramMap.put("endTime", DateUtil.format(req.getEndTime())); } if (req.getOffset() != null) { paramMap.put("offset", req.getOffset()); } if (req.getLimit() != null) { paramMap.put("limit", req.getLimit()); } } String respData = ApiUtils.getApi(baseApiUrl + Constant.DESK_API_URI.GET_STATUS_HISTORY, paramMap, this.getToken()); return respData; } }
三:常量類
package com.jianlejun.dto; public class Constant { public static class LOCK_STATUS { public static final String LOCK_STATUS_ON = "on"; public static final String LOCK_STATUS_OFF = "off"; } public static class DESK_API_URI{ public static final String GET_TOKEN = "/api/token"; public static final String GET_DESKS = "/xxx/ids"; public static final String GET_STATUS = "/xxx/status"; ) public static final String ADJUST_HEIGHT = "/xxx/{deskId}/xxx"; public static final String ADJUST_LOCK_STATUS = "/xxx/{deskId}/xxx"; public static final String GET_STATUS_HISTORY = "/xxx/xxxx"; } }
四:測試類
public class Test {
public static void main(String[] args) throws ClientProtocolException, URISyntaxException, IOException, ParseException {
Client c = new Client();
List<String> ids = new ArrayList();
ids.add("1234567-da60-40fb-b14b-35c553b22899");
ids.add("7654321-eb62-4dab-be32-9de0065f3bd2");
System.out.println(c.getStatus(ids));
}
}
五:DTO
package com.jianlejun.request;
public class GetTokenRequest {
private String unique_name;
private String password;
public GetTokenRequest(String uniqueName, String password) {
this.unique_name = uniqueName;
this.password = password;
}
public String getUnique_name() {
return unique_name;
}
public void setUnique_name(String unique_name) {
this.unique_name = unique_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}