PageRenderTime 62ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/zaiqingchen/wechat-mp-sdk
Java | 129 lines | 104 code | 18 blank | 7 comment | 13 complexity | b80ce6e35f11f8a5ad2e80f86014262d 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 final static 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. /**
  43. * handle response's entity to utf8 text
  44. */
  45. public static final ResponseHandler<String> UTF8_CONTENT_HANDLER = new ResponseHandler<String>() {
  46. @Override
  47. public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  48. final StatusLine statusLine = response.getStatusLine();
  49. if (statusLine.getStatusCode() >= 300) {
  50. throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
  51. }
  52. final HttpEntity entity = response.getEntity();
  53. if (entity != null) {
  54. return EntityUtils.toString(entity, "UTF-8");
  55. }
  56. return StringUtils.EMPTY;
  57. }
  58. };
  59. public static <T extends JsonRtn> T getRequest(WechatRequest request, License license, Class<T> jsonRtnClazz) {
  60. return getRequest(request, license, null, jsonRtnClazz);
  61. }
  62. public static <T extends JsonRtn> T getRequest(WechatRequest request, License license, Map<String, String> paramMap, Class<T> jsonRtnClazz) {
  63. String requestUrl = request.getUrl();
  64. String requestName = request.getName();
  65. List<NameValuePair> nameValuePairs = buildNameValuePairs(license, paramMap);
  66. try {
  67. URI uri = new URIBuilder(requestUrl).setParameters(nameValuePairs).build();
  68. String json = Request.Get(uri).execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);
  69. T jsonRtn = JsonRtnUtil.parseJsonRtn(json, jsonRtnClazz);
  70. log.info(requestName + " result:\n url={},\n rtn={},\n {}", uri, json, jsonRtn);
  71. return jsonRtn;
  72. } catch (Exception e) {
  73. String msg = requestName + " failed:\n url=" + requestUrl + "\n params=" + nameValuePairs;
  74. log.error(msg, e);
  75. return null;
  76. }
  77. }
  78. public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Object requestBody, Class<T> jsonRtnClazz) {
  79. return postBodyRequest(request, license, null, requestBody, jsonRtnClazz);
  80. }
  81. public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Map<String, String> paramMap, Object requestBody, Class<T> jsonRtnClazz) {
  82. if (request == null || license == null || requestBody == null || jsonRtnClazz == null) {
  83. return null;
  84. }
  85. String requestUrl = request.getUrl();
  86. String requestName = request.getName();
  87. List<NameValuePair> nameValuePairs = buildNameValuePairs(license, paramMap);
  88. String body = JSONObject.toJSONString(requestBody);
  89. try {
  90. URI uri = new URIBuilder(requestUrl).setParameters(nameValuePairs).build();
  91. String rtnJson = Request.Post(uri)
  92. .bodyString(body, ContentType.create("text/html", Consts.UTF_8))
  93. .execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);
  94. T jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, jsonRtnClazz);
  95. log.info(requestName + " result:\n url={},\n body={},\n rtn={},\n {}", uri, body, rtnJson, jsonRtn);
  96. return jsonRtn;
  97. } catch (Exception e) {
  98. String msg = requestName + " failed:\n url=" + requestUrl + "\n params=" + nameValuePairs + ",\n body=" + body;
  99. log.error(msg, e);
  100. return null;
  101. }
  102. }
  103. private static List<NameValuePair> buildNameValuePairs(License license, Map<String, String> paramMap) {
  104. List<NameValuePair> nameValuePairs = Lists.newArrayList();
  105. nameValuePairs.add(new BasicNameValuePair("access_token", AccessTokenUtil.getAccessToken(license)));
  106. if (paramMap != null) {
  107. Iterables.addAll(nameValuePairs, Iterables.transform(paramMap.entrySet(), nameValueTransformFunction));
  108. }
  109. return nameValuePairs;
  110. }
  111. }