PageRenderTime 64ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

/wechat-mp-sdk/src/main/java/org/usc/wechat/mp/sdk/util/HttpUtil.java

https://gitlab.com/hackbuteer59/wechat-mp-sdk
Java | 177 lines | 142 code | 28 blank | 7 comment | 21 complexity | ecd590ee9078d951b5d5c3d2fa73e18d MD5 | raw file
  1. package org.usc.wechat.mp.sdk.util;
  2. import java.io.IOException;
  3. import java.net.URI;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.apache.commons.lang3.StringUtils;
  7. import org.apache.http.Consts;
  8. import org.apache.http.HttpEntity;
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.StatusLine;
  12. import org.apache.http.client.ClientProtocolException;
  13. import org.apache.http.client.HttpResponseException;
  14. import org.apache.http.client.ResponseHandler;
  15. import org.apache.http.client.fluent.Request;
  16. import org.apache.http.client.utils.URIBuilder;
  17. import org.apache.http.entity.ContentType;
  18. import org.apache.http.message.BasicNameValuePair;
  19. import org.apache.http.util.EntityUtils;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import org.usc.wechat.mp.sdk.util.platform.AccessTokenUtil;
  23. import org.usc.wechat.mp.sdk.vo.JsonRtn;
  24. import org.usc.wechat.mp.sdk.vo.WechatRequest;
  25. import org.usc.wechat.mp.sdk.vo.token.License;
  26. import com.alibaba.fastjson.JSONObject;
  27. import com.google.common.base.Function;
  28. import com.google.common.collect.Iterables;
  29. import com.google.common.collect.Lists;
  30. /**
  31. *
  32. * @author Shunli
  33. */
  34. public class HttpUtil {
  35. private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
  36. private static final Function<Map.Entry<String, String>, NameValuePair> nameValueTransformFunction = new Function<Map.Entry<String, String>, NameValuePair>() {
  37. @Override
  38. public NameValuePair apply(final Map.Entry<String, String> input) {
  39. return new BasicNameValuePair(input.getKey(), input.getValue());
  40. }
  41. };
  42. public static final int CONNECT_TIMEOUT = 2000;
  43. public static final int SOCKET_TIMEOUT = 2000;
  44. /**
  45. * handle response's entity to utf8 text
  46. */
  47. public static final ResponseHandler<String> UTF8_CONTENT_HANDLER = new ResponseHandler<String>() {
  48. @Override
  49. public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  50. final StatusLine statusLine = response.getStatusLine();
  51. if (statusLine.getStatusCode() >= 300) {
  52. throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
  53. }
  54. final HttpEntity entity = response.getEntity();
  55. if (entity != null) {
  56. return EntityUtils.toString(entity, "UTF-8");
  57. }
  58. return StringUtils.EMPTY;
  59. }
  60. };
  61. public static <T extends JsonRtn> T getRequest(WechatRequest request, License license, Class<T> jsonRtnClazz) {
  62. return getRequest(request, license, null, jsonRtnClazz);
  63. }
  64. public static <T extends JsonRtn> T getRequest(WechatRequest request, License license, Map<String, String> paramMap, Class<T> jsonRtnClazz) {
  65. String requestUrl = request.getUrl();
  66. String requestName = request.getName();
  67. List<NameValuePair> nameValuePairs = buildNameValuePairs(license, paramMap);
  68. URI uri = buildURI(requestUrl, nameValuePairs);
  69. if (uri == null) {
  70. return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "build request URI failed");
  71. }
  72. try {
  73. String json = Request.Get(uri)
  74. .connectTimeout(CONNECT_TIMEOUT)
  75. .socketTimeout(SOCKET_TIMEOUT)
  76. .execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);
  77. T jsonRtn = JsonRtnUtil.parseJsonRtn(json, jsonRtnClazz);
  78. log.info(requestName + " result:\n url={},\n rtn={},\n {}", uri, json, jsonRtn);
  79. return jsonRtn;
  80. } catch (Exception e) {
  81. String msg = requestName + " failed:\n url=" + uri;
  82. log.error(msg, e);
  83. return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "get request server failed");
  84. }
  85. }
  86. public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Object requestBody, Class<T> jsonRtnClazz) {
  87. return postBodyRequest(request, license, null, requestBody, jsonRtnClazz);
  88. }
  89. public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Map<String, String> paramMap, Class<T> jsonRtnClazz) {
  90. return postBodyRequest(request, license, paramMap, null, jsonRtnClazz);
  91. }
  92. public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Map<String, String> paramMap, Object requestBody, Class<T> jsonRtnClazz) {
  93. if (request == null || license == null || jsonRtnClazz == null) {
  94. return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "missing post request params");
  95. }
  96. String requestUrl = request.getUrl();
  97. String requestName = request.getName();
  98. List<NameValuePair> form = buildNameValuePairs(paramMap);
  99. String body = requestBody != null ? JSONObject.toJSONString(requestBody) : StringUtils.EMPTY;
  100. URI uri = buildURI(requestUrl, buildNameValuePairs(license));
  101. if (uri == null) {
  102. return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "build request URI failed");
  103. }
  104. try {
  105. Request post = Request.Post(uri)
  106. .connectTimeout(CONNECT_TIMEOUT)
  107. .socketTimeout(SOCKET_TIMEOUT);
  108. if (paramMap != null) {
  109. post.bodyForm(form);
  110. }
  111. if (StringUtils.isNoneEmpty(body)) {
  112. post.bodyString(body, ContentType.create("text/html", Consts.UTF_8));
  113. }
  114. String rtnJson = post.execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);
  115. T jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, jsonRtnClazz);
  116. log.info(requestName + " result:\n url={},\n form={},\n body={},\n rtn={},\n {}", uri, form, body, rtnJson, jsonRtn);
  117. return jsonRtn;
  118. } catch (Exception e) {
  119. String msg = requestName + " failed:\n url=" + uri + ",\n form=" + form + ",\n body=" + body;
  120. log.error(msg, e);
  121. return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "post request server failed");
  122. }
  123. }
  124. private static List<NameValuePair> buildNameValuePairs(License license) {
  125. return buildNameValuePairs(license, null);
  126. }
  127. private static List<NameValuePair> buildNameValuePairs(Map<String, String> paramMap) {
  128. return buildNameValuePairs(null, paramMap);
  129. }
  130. private static List<NameValuePair> buildNameValuePairs(License license, Map<String, String> paramMap) {
  131. List<NameValuePair> nameValuePairs = Lists.newArrayList();
  132. if (license != null) {
  133. nameValuePairs.add(new BasicNameValuePair("access_token", AccessTokenUtil.getAccessToken(license)));
  134. }
  135. if (paramMap != null) {
  136. Iterables.addAll(nameValuePairs, Iterables.transform(paramMap.entrySet(), nameValueTransformFunction));
  137. }
  138. return nameValuePairs;
  139. }
  140. private static URI buildURI(String requestUrl, List<NameValuePair> nameValuePairs) {
  141. try {
  142. return new URIBuilder(requestUrl).setParameters(nameValuePairs).build();
  143. } catch (Exception e) {
  144. String msg = "build URI failed:\n url=" + requestUrl + "\n params=" + nameValuePairs;
  145. log.error(msg, e);
  146. return null;
  147. }
  148. }
  149. }