HttpUtils.java 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package com.kingdee.eas.custom.wamke.syncdata.utils;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. import java.util.Map;
  9. import org.apache.http.HttpEntity;
  10. import org.apache.http.client.ClientProtocolException;
  11. import org.apache.http.client.methods.CloseableHttpResponse;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.entity.StringEntity;
  14. import org.apache.http.impl.client.CloseableHttpClient;
  15. import org.apache.http.impl.client.HttpClientBuilder;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.message.BasicHeader;
  18. import org.apache.http.protocol.HTTP;
  19. import org.apache.http.util.EntityUtils;
  20. import org.apache.log4j.Logger;
  21. import com.kingdee.bos.BOSException;
  22. import com.kingdee.eas.custom.constants.Constants;
  23. import com.kingdee.eas.custom.utils.ObjectUtils;
  24. import com.kingdee.eas.custom.utils.StringUtils;
  25. public class HttpUtils {
  26. private static Logger logger =
  27. Logger.getLogger("com.kingdee.eas.custom.wamke.utils.HttpUtils");
  28. private static final int MAX_CONNECT_TIMEOUT = 10000;
  29. private static final int MAX_SOCKET_TIMEOUT = 60000;
  30. public static String sendGet(String url, String param){
  31. return sendGet(url,param, "UTF_8");
  32. }
  33. /**
  34. * 向指定 URL 发送GET方法的请求
  35. *
  36. * @param url 发送请求的 URL
  37. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  38. * @param contentType 编码类型
  39. * @return 所代表远程资源的响应结果
  40. * @throws BOSException
  41. */
  42. public static String sendGet(String url, String param, String contentType) {
  43. StringBuilder result = new StringBuilder();
  44. BufferedReader in = null;
  45. try {
  46. String urlNameString = (param!=null&&param!="") ? url + "?" + param : url;
  47. URL realUrl = new URL(urlNameString);
  48. System.out.println("请求URL:"+realUrl);
  49. URLConnection connection = realUrl.openConnection();
  50. connection.setRequestProperty("accept", "*/*");
  51. connection.setRequestProperty("connection", "Keep-Alive");
  52. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  53. connection.connect();
  54. in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
  55. String line;
  56. while ((line = in.readLine()) != null) {
  57. result.append(line);
  58. }
  59. } catch (Exception e) {
  60. logger.error(e.getMessage());
  61. e.printStackTrace();
  62. } finally {
  63. try {
  64. if (in != null) {
  65. in.close();
  66. }
  67. } catch (Exception ex) {
  68. logger.error(ex.getMessage());
  69. }
  70. }
  71. return result.toString();
  72. }
  73. /**
  74. * @param url
  75. * @param paramMap
  76. * @param contentType
  77. * @return
  78. */
  79. public static String sendGet(String url, Map<String, String> paramMap, String contentType) {
  80. StringBuilder sb = new StringBuilder();
  81. if (null != paramMap && !paramMap.isEmpty()) {
  82. for (Map.Entry<String,String> entry : paramMap.entrySet()) {
  83. if (sb.length() > 0) {
  84. sb.append("&");
  85. }
  86. sb.append(entry.getKey()).append("=").append(entry.getValue());
  87. }
  88. }
  89. if (StringUtils.isBlank(contentType)) {
  90. contentType = Constants.UTF8;
  91. }
  92. return sendGet(url, sb.toString(), contentType);
  93. }
  94. /**
  95. * 发送post请求
  96. * @param uri
  97. * @param paramStr
  98. * @return
  99. */
  100. public static String sendPost(String uri, String paramStr){
  101. return sendPost(uri,paramStr,null);
  102. }
  103. /**
  104. * 发送post请求
  105. * @param uri 请求地址
  106. * @param paramStr 请求的JSON数据
  107. * @param token 头部token
  108. * @return
  109. */
  110. public static String sendPost(String uri, String paramStr, String token) {
  111. // 创建默认的httpClient实例.
  112. CloseableHttpClient httpclient = HttpClients.createDefault();
  113. // 创建httpPost
  114. HttpPost httppost = new HttpPost(uri);
  115. // 创建参数队列
  116. StringEntity uefEntity = null;
  117. String result = null;
  118. try {
  119. String reqJson = paramStr; // JSON.toJSONString(paramsMap);
  120. uefEntity = new StringEntity(reqJson, "UTF-8");
  121. uefEntity.setContentType("text/json");
  122. uefEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  123. httppost.setEntity(uefEntity);
  124. httppost.setHeader("Content-Type", "application/json");
  125. if (ObjectUtils.isNotEmpty(token)) {
  126. httppost.setHeader("Authorization", token);
  127. }
  128. CloseableHttpResponse response = httpclient.execute(httppost);
  129. if (response.getStatusLine().getStatusCode() != 200) {
  130. String msg = "http请求处理异常.";
  131. msg += response.toString();
  132. }
  133. try {
  134. HttpEntity entity = response.getEntity();
  135. if (entity != null) {
  136. result = EntityUtils.toString(entity, "UTF-8");
  137. }
  138. } finally {
  139. response.close();
  140. }
  141. } catch (ClientProtocolException e) {
  142. logger.error(e.getMessage(), e);
  143. } catch (UnsupportedEncodingException e1) {
  144. logger.error(e1.getMessage(), e1);
  145. } catch (IOException e) {
  146. logger.error(e.getMessage(), e);
  147. } finally {
  148. // 关闭连接,释放资源
  149. try {
  150. httpclient.close();
  151. } catch (IOException e) {
  152. logger.error(e.getMessage(), e);
  153. }
  154. }
  155. return result;
  156. }
  157. /**
  158. * XML/JSON入参的HTTP交互
  159. * @param url
  160. * @param contentType
  161. * @param headers
  162. * @param content XML/JSON数据
  163. * @param httpConnectTimeout
  164. * @param httpSocketTimeout
  165. * @param httpSocketTimeout
  166. * @return outLogs 输出全量日志
  167. * @Author KangLG<2 0 2 2 年8月11日>
  168. */
  169. public static String postRemote(String url, String contentType, Map<String, String> headers, String content, int httpConnectTimeout, int httpSocketTimeout, boolean outLogs) {
  170. String result = null;
  171. try {
  172. HttpPost post = new HttpPost(url.trim());
  173. post.setEntity(new StringEntity(content, "UTF-8"));
  174. post.setHeader("Content-Type", null != contentType ? contentType : "application/json");
  175. if (null != headers && !headers.isEmpty()) {
  176. for (Map.Entry<String, String> item : headers.entrySet()) {
  177. post.setHeader(item.getKey(), item.getValue());
  178. }
  179. }
  180. //设置请求和传输超时时间
  181. // RequestConfig requestConfig = RequestConfig.custom()
  182. // .setConnectTimeout(httpConnectTimeout > 0 ? httpConnectTimeout : MAX_CONNECT_TIMEOUT)
  183. // .setSocketTimeout(httpSocketTimeout > 0 ? httpSocketTimeout : MAX_SOCKET_TIMEOUT)
  184. // .build();
  185. // post. (requestConfig);
  186. CloseableHttpClient httpclient = HttpClientBuilder.create().build();
  187. CloseableHttpResponse response = httpclient.execute(post);
  188. HttpEntity responseEntity = response.getEntity();
  189. System.out.println(String.format("[%s]响应信息: ContentType=%s, 状态=%s", url, null != responseEntity ? responseEntity.getContentType() : "null", response.getStatusLine()));
  190. if (null == responseEntity) {
  191. return null;
  192. }
  193. result = EntityUtils.toString(responseEntity);
  194. if(outLogs){
  195. logger.info(String.format("[%s]响应内容: %s", url, result));
  196. System.out.println(String.format("[%s]响应内容: %s", url, result));
  197. }
  198. return result;
  199. } catch (Exception e) {
  200. e.printStackTrace();
  201. logger.error("推送异常/" + e.toString() + ": " + content);
  202. return null;
  203. }
  204. }
  205. }