HTTPHelper.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package com.malk.hengyilong.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.*;
  5. import java.net.HttpURLConnection;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;
  8. import java.net.UnknownHostException;
  9. import java.text.MessageFormat;
  10. import java.util.HashMap;
  11. import java.util.LinkedHashMap;
  12. import java.util.Map.Entry;
  13. public class HTTPHelper {
  14. // slf4j日志记录器
  15. private static final Logger LOG = LoggerFactory.getLogger(HTTPHelper.class);
  16. /***
  17. * 向指定URL发送GET方法的请求
  18. *
  19. * @param apiUrl
  20. * @param data
  21. * @param projectId
  22. * @param signature
  23. * @param encoding
  24. * @return
  25. * @throws Exception
  26. */
  27. public static String sendGet(String apiUrl, HashMap<String, Object> param,
  28. LinkedHashMap<String, String> headers, String encoding) throws Exception {
  29. // 获得响应内容
  30. String http_RespContent = null;
  31. HttpURLConnection httpURLConnection = null;
  32. int http_StatusCode = 0;
  33. String http_RespMessage = null;
  34. try {
  35. // 实际请求完整Url
  36. StringBuffer fullUrl = new StringBuffer();
  37. if (null != param) {
  38. if (0 != param.size()) {
  39. StringBuffer params = new StringBuffer();
  40. for (Entry<String, Object> entry : param.entrySet()) {
  41. params.append(entry.getKey());
  42. params.append("=");
  43. params.append(entry.getValue().toString());
  44. params.append("&");
  45. }
  46. if (params.length() > 0) {
  47. params.deleteCharAt(params.lastIndexOf("&"));
  48. }
  49. fullUrl.append(apiUrl).append((params.length() > 0) ? "?" + params.toString() : "");
  50. } else {
  51. fullUrl.append(apiUrl);
  52. }
  53. } else {
  54. fullUrl.append(apiUrl);
  55. }
  56. LOG.info(">>>> 实际请求Url: " + fullUrl.toString());
  57. // 建立连接
  58. URL url = new URL(fullUrl.toString());
  59. httpURLConnection = (HttpURLConnection) url.openConnection();
  60. // 需要输出
  61. httpURLConnection.setDoOutput(true);
  62. // 需要输入
  63. httpURLConnection.setDoInput(true);
  64. // 不允许缓存
  65. httpURLConnection.setUseCaches(false);
  66. // HTTP请求方式
  67. httpURLConnection.setRequestMethod("GET");
  68. // 设置Headers
  69. if (null != headers) {
  70. for (String key : headers.keySet()) {
  71. httpURLConnection.setRequestProperty(key, headers.get(key));
  72. }
  73. }
  74. // 连接会话
  75. httpURLConnection.connect();
  76. // 获得响应状态(HTTP状态码)
  77. http_StatusCode = httpURLConnection.getResponseCode();
  78. // 获得响应消息(HTTP状态码描述)
  79. http_RespMessage = httpURLConnection.getResponseMessage();
  80. // 获得响应内容
  81. if (HttpURLConnection.HTTP_OK == http_StatusCode) {
  82. // 返回响应结果
  83. http_RespContent = getResponseContent(httpURLConnection);
  84. } else {
  85. // 返回非200状态时响应结果
  86. http_RespContent = getErrorResponseContent(httpURLConnection);
  87. String msg =
  88. MessageFormat.format("请求失败: Http状态码 = {0} , {1}", http_StatusCode, http_RespMessage);
  89. LOG.info(msg);
  90. }
  91. } catch (UnknownHostException e) {
  92. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  93. Exception ex = new Exception(message);
  94. ex.initCause(e);
  95. throw ex;
  96. } catch (MalformedURLException e) {
  97. String message = MessageFormat.format("格式错误的URL: {0}", e.getMessage());
  98. Exception ex = new Exception(message);
  99. ex.initCause(e);
  100. throw ex;
  101. } catch (IOException e) {
  102. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  103. Exception ex = new Exception(message);
  104. ex.initCause(e);
  105. throw ex;
  106. } catch (Exception e) {
  107. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  108. Exception ex = new Exception(message);
  109. ex.initCause(e);
  110. throw ex;
  111. } finally {
  112. if (null != httpURLConnection) {
  113. httpURLConnection.disconnect();
  114. }
  115. }
  116. return http_RespContent;
  117. }
  118. /***
  119. * 向指定URL发送POST方法的请求
  120. *
  121. * @param apiUrl
  122. * @param data
  123. * @param projectId
  124. * @param signature
  125. * @param encoding
  126. * @return
  127. * @throws Exception
  128. */
  129. public static String sendPOST(String apiUrl, String data, LinkedHashMap<String, String> headers,
  130. String encoding) throws Exception {
  131. // 获得响应内容
  132. String http_RespContent = null;
  133. HttpURLConnection httpURLConnection = null;
  134. int http_StatusCode = 0;
  135. String http_RespMessage = null;
  136. try {
  137. // 建立连接
  138. URL url = new URL(apiUrl);
  139. httpURLConnection = (HttpURLConnection) url.openConnection();
  140. // 需要输出
  141. httpURLConnection.setDoOutput(true);
  142. // 需要输入
  143. httpURLConnection.setDoInput(true);
  144. // 不允许缓存
  145. httpURLConnection.setUseCaches(false);
  146. // HTTP请求方式
  147. httpURLConnection.setRequestMethod("POST");
  148. // 设置Headers
  149. if (null != headers) {
  150. for (String key : headers.keySet()) {
  151. httpURLConnection.setRequestProperty(key, headers.get(key));
  152. }
  153. }
  154. // 连接会话
  155. httpURLConnection.connect();
  156. // 建立输入流,向指向的URL传入参数
  157. DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
  158. // 设置请求参数
  159. dos.write(data.getBytes(encoding));
  160. dos.flush();
  161. dos.close();
  162. // 获得响应状态(HTTP状态码)
  163. http_StatusCode = httpURLConnection.getResponseCode();
  164. // 获得响应消息(HTTP状态码描述)
  165. http_RespMessage = httpURLConnection.getResponseMessage();
  166. // 获得响应内容
  167. if (HttpURLConnection.HTTP_OK == http_StatusCode) {
  168. // 返回响应结果
  169. http_RespContent = getResponseContent(httpURLConnection);
  170. } else {
  171. // 返回非200状态时响应结果
  172. http_RespContent = getErrorResponseContent(httpURLConnection);
  173. String msg =
  174. MessageFormat.format("请求失败: Http状态码 = {0} , {1}", http_StatusCode, http_RespMessage);
  175. LOG.info(msg);
  176. }
  177. } catch (UnknownHostException e) {
  178. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  179. Exception ex = new Exception(message);
  180. ex.initCause(e);
  181. throw ex;
  182. } catch (MalformedURLException e) {
  183. String message = MessageFormat.format("格式错误的URL: {0}", e.getMessage());
  184. Exception ex = new Exception(message);
  185. ex.initCause(e);
  186. throw ex;
  187. } catch (IOException e) {
  188. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  189. Exception ex = new Exception(message);
  190. ex.initCause(e);
  191. throw ex;
  192. } catch (Exception e) {
  193. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  194. Exception ex = new Exception(message);
  195. ex.initCause(e);
  196. throw ex;
  197. } finally {
  198. if (null != httpURLConnection) {
  199. httpURLConnection.disconnect();
  200. }
  201. }
  202. return http_RespContent;
  203. }
  204. /***
  205. * 读取HttpResponse响应内容
  206. *
  207. * @param httpURLConnection
  208. * @return
  209. * @throws UnsupportedEncodingException
  210. * @throws IOException
  211. */
  212. private static String getResponseContent(HttpURLConnection httpURLConnection)
  213. throws UnsupportedEncodingException, IOException {
  214. StringBuffer contentBuffer = null;
  215. BufferedReader responseReader = null;
  216. try {
  217. contentBuffer = new StringBuffer();
  218. String readLine = null;
  219. responseReader =
  220. new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
  221. while ((readLine = responseReader.readLine()) != null) {
  222. contentBuffer.append(readLine);
  223. }
  224. } finally {
  225. if (null != responseReader) {
  226. responseReader.close();
  227. }
  228. }
  229. return contentBuffer.toString();
  230. }
  231. /***
  232. * 读取HttpResponse响应内容
  233. *
  234. * @param httpURLConnection
  235. * @return
  236. * @throws UnsupportedEncodingException
  237. * @throws IOException
  238. */
  239. private static String getErrorResponseContent(HttpURLConnection httpURLConnection)
  240. throws UnsupportedEncodingException, IOException {
  241. StringBuffer contentBuffer = null;
  242. BufferedReader responseReader = null;
  243. try {
  244. contentBuffer = new StringBuffer();
  245. String readLine = null;
  246. responseReader =
  247. new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
  248. while ((readLine = responseReader.readLine()) != null) {
  249. contentBuffer.append(readLine);
  250. }
  251. } finally {
  252. if (null != responseReader) {
  253. responseReader.close();
  254. }
  255. }
  256. return contentBuffer.toString();
  257. }
  258. }