HttpClientUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package com.szwl.model.utils;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.HttpStatus;
  6. import org.apache.http.client.ClientProtocolException;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.CloseableHttpResponse;
  10. import org.apache.http.client.methods.HttpGet;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.config.ConnectionConfig;
  13. import org.apache.http.config.Registry;
  14. import org.apache.http.config.RegistryBuilder;
  15. import org.apache.http.config.SocketConfig;
  16. import org.apache.http.conn.socket.ConnectionSocketFactory;
  17. import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
  18. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  19. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  20. import org.apache.http.conn.ssl.SSLContexts;
  21. import org.apache.http.conn.ssl.TrustStrategy;
  22. import org.apache.http.entity.StringEntity;
  23. import org.apache.http.impl.client.CloseableHttpClient;
  24. import org.apache.http.impl.client.HttpClientBuilder;
  25. import org.apache.http.impl.client.HttpClients;
  26. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  27. import org.apache.http.message.BasicNameValuePair;
  28. import org.apache.http.util.EntityUtils;
  29. import org.apache.log4j.Logger;
  30. import org.dom4j.Document;
  31. import org.dom4j.io.SAXReader;
  32. import org.json.JSONObject;
  33. import org.json.JSONTokener;
  34. import javax.net.ssl.SSLContext;
  35. import javax.servlet.http.HttpServletRequest;
  36. import java.io.IOException;
  37. import java.io.InputStream;
  38. import java.io.InputStreamReader;
  39. import java.io.UnsupportedEncodingException;
  40. import java.nio.charset.Charset;
  41. import java.security.KeyManagementException;
  42. import java.security.KeyStore;
  43. import java.security.KeyStoreException;
  44. import java.security.NoSuchAlgorithmException;
  45. import java.security.cert.CertificateException;
  46. import java.security.cert.X509Certificate;
  47. import java.util.HashMap;
  48. import java.util.List;
  49. import java.util.Map;
  50. /**
  51. * Created by study on 6/26/2015 11:30.
  52. */
  53. public final class HttpClientUtils {
  54. private static Logger logger = Logger.getLogger("HttpClientUtils");
  55. public final static String Order_Url = "http://app.sunzee.com.cn/ShenzeeServer/EsApi/getOrder";
  56. public final static String Update_Order_Url = "http://app.sunzee.com.cn/ShenzeeServer/EsApi/updateOrder";
  57. // public final static String Es_Order_Url = "http://app.sunzee.com.cn/ShenzeeServer/EsApi/getOrder";
  58. public final static String CoinOrder_Url = "http://app.sunzee.com.cn/ShenzeeServer/EsApi/getCoinOrder";
  59. // public final static String Es_CoinOrder_Url = "http://app.sunzee.com.cn/ShenzeeServer/EsApi/getCoinOrder";
  60. public final static String Equipment_Url = "http://app.sunzee.com.cn/ShenzeeServer/EsApi/getEquipment";
  61. public final static String Update_Equipment_Url = "http://app.sunzee.com.cn/ShenzeeServer/EsApi/updateEquipment";
  62. private HttpClientUtils() {
  63. }
  64. /**
  65. * post xml
  66. *
  67. * @param url
  68. * @param xml
  69. * @return
  70. */
  71. public static String postXml(String url, String xml) throws IOException {
  72. HttpClient client = HttpClientBuilder.create().build();
  73. client = WebClientDevWrapper.wrapClient(client);
  74. HttpPost post = new HttpPost(url);
  75. String response = null;
  76. InputStream instream = null;
  77. try {
  78. StringEntity s = new StringEntity(xml, "UTF-8");
  79. s.setContentEncoding("UTF-8");
  80. s.setContentType("application/xml");
  81. post.setEntity(s);
  82. HttpResponse res = null;
  83. if (client != null) {
  84. res = client.execute(post);
  85. }
  86. if (res != null && res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  87. HttpEntity entity = res.getEntity();
  88. SAXReader reader = new SAXReader();
  89. instream = entity.getContent();
  90. Document document = reader.read(new InputStreamReader(instream, "utf-8"));
  91. response = document.asXML();
  92. }
  93. } catch (Exception e) {
  94. throw new RuntimeException(e);
  95. } finally {
  96. if (instream != null) {
  97. instream.close();
  98. }
  99. }
  100. return response;
  101. }
  102. /**
  103. * post json
  104. *
  105. * @param url
  106. * @param json
  107. * @return
  108. */
  109. public static JSONObject postJson(String url, String json) throws IOException {
  110. HttpClient client = HttpClientBuilder.create().build();
  111. client = WebClientDevWrapper.wrapClient(client);
  112. HttpPost post = new HttpPost(url);
  113. JSONObject response = null;
  114. InputStream instream = null;
  115. try {
  116. StringEntity s = new StringEntity(json, "UTF-8");
  117. s.setContentEncoding("UTF-8");
  118. s.setContentType("application/json");
  119. post.setEntity(s);
  120. HttpResponse res = null;
  121. if (client != null) {
  122. res = client.execute(post);
  123. }
  124. if (res != null && res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  125. HttpEntity entity = res.getEntity();
  126. String charset = "utf-8";
  127. instream = entity.getContent();
  128. response = new JSONObject(new JSONTokener(new InputStreamReader(instream, charset)));
  129. }
  130. } catch (Exception e) {
  131. throw new RuntimeException(e);
  132. } finally {
  133. if (instream != null) {
  134. instream.close();
  135. }
  136. }
  137. return response;
  138. }
  139. /**
  140. * java httpClient4.5 post请求
  141. */
  142. @SuppressWarnings("unchecked")
  143. public static String sendPost(String sendMsg, String sendUrl) {
  144. HttpPost httpPost = new HttpPost(sendUrl);
  145. HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  146. CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
  147. StringEntity entity;
  148. String status = "false";
  149. Map<String,Object> mres = new HashMap<String, Object>();
  150. try {
  151. entity = new StringEntity(sendMsg, "UTF-8"); //解决参数中文乱码问题
  152. entity.setContentEncoding("UTF-8");//设置编码格式
  153. entity.setContentType("application/json");
  154. httpPost.setEntity(entity);
  155. // 发起请求
  156. HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
  157. // 请求结束,返回结果。并解析json。
  158. String resData = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
  159. status = resData;
  160. // Map map = JSON.parseObject(JSON.toJSONString(resData), Map.class);
  161. // mres = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(resData), Map.class);
  162. // mres = (Map<String, Object>) JSONObject.toBean(JSONObject.fromObject(resData), Map.class);
  163. } catch (Exception e) {
  164. e.printStackTrace();
  165. } finally {
  166. if (null != closeableHttpClient) {
  167. try {
  168. closeableHttpClient.close();
  169. } catch (Exception e) {
  170. e.printStackTrace();
  171. }
  172. }
  173. }
  174. return status;
  175. // return mres;
  176. }
  177. /**
  178. * 从request中获取请求方IP
  179. * @param request
  180. * @return
  181. */
  182. public static String getIpAddress(HttpServletRequest request) {
  183. String ip = request.getHeader("x-forwarded-for");
  184. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  185. ip = request.getHeader("Proxy-Client-IP");
  186. }
  187. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  188. ip = request.getHeader("WL-Proxy-Client-IP");
  189. }
  190. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  191. ip = request.getHeader("HTTP_CLIENT_IP");
  192. }
  193. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  194. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  195. }
  196. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  197. // 若以上方式均为获取到ip则证明获得客户端并没有采用反向代理直接使用getRemoteAddr()获取客户端的ip地址
  198. ip = request.getRemoteAddr();
  199. }
  200. // 多个路由时,取第一个非unknown的ip
  201. final String[] arr = ip.split(",");
  202. for (final String str : arr) {
  203. if (!"unknown".equalsIgnoreCase(str)) {
  204. ip = str;
  205. break;
  206. }
  207. }
  208. return ip;
  209. }
  210. /**
  211. * post 键值对
  212. *
  213. * @param url
  214. * @param data 键值对内容
  215. * @return
  216. */
  217. public static String sentData(String url, String data) {
  218. if(!StringUtils.isEmpty(url)&&!StringUtils.isEmpty(data)){
  219. String result = sendPost(data, url);
  220. return result;
  221. }
  222. return "400";
  223. }
  224. /**
  225. * post 键值对
  226. *
  227. * @param url
  228. * @param data 键值对内容
  229. * @return
  230. */
  231. public static String postKeyValue(String url, List<BasicNameValuePair> data) {
  232. CloseableHttpClient httpClient = getHttpClient();
  233. try {
  234. HttpPost post = new HttpPost(url);
  235. //url格式编码
  236. UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(data, "UTF-8");
  237. post.setEntity(uefEntity);
  238. CloseableHttpResponse httpResponse = httpClient.execute(post);
  239. HttpEntity entity = httpResponse.getEntity();
  240. try {
  241. if (null != entity) {
  242. String result = EntityUtils.toString(entity);
  243. return result;
  244. }
  245. } finally {
  246. httpResponse.close();
  247. }
  248. } catch (UnsupportedEncodingException e) {
  249. e.printStackTrace();
  250. } catch (ClientProtocolException e) {
  251. e.printStackTrace();
  252. } catch (IOException e) {
  253. e.printStackTrace();
  254. } finally {
  255. try {
  256. closeHttpClient(httpClient);
  257. } catch (IOException e) {
  258. e.printStackTrace();
  259. }
  260. }
  261. return null;
  262. }
  263. /**
  264. * get json
  265. *
  266. * @param url
  267. * @return
  268. */
  269. public static JSONObject get(String url) throws IOException {
  270. HttpClient client = HttpClientBuilder.create().build();
  271. client = WebClientDevWrapper.wrapClient(client);
  272. HttpGet get = new HttpGet(url);
  273. JSONObject response = null;
  274. InputStream instream = null;
  275. try {
  276. HttpResponse res = null;
  277. if (client != null) {
  278. res = client.execute(get);
  279. }
  280. if (res != null && res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  281. HttpEntity entity = res.getEntity();
  282. instream = entity.getContent();
  283. response = new JSONObject(new JSONTokener(new InputStreamReader(instream, "utf-8")));
  284. }
  285. } catch (Exception e) {
  286. throw new RuntimeException(e);
  287. } finally {
  288. if (instream != null) {
  289. instream.close();
  290. }
  291. }
  292. return response;
  293. }
  294. private static class WebClientDevWrapper {
  295. public static HttpClient wrapClient(HttpClient base) {
  296. try {
  297. RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  298. ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
  299. registryBuilder.register("http", plainSF);
  300. //指定信任密钥存储对象和连接套接字工厂
  301. try {
  302. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  303. SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
  304. LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  305. registryBuilder.register("https", sslSF);
  306. } catch (KeyStoreException e) {
  307. throw new RuntimeException(e);
  308. } catch (KeyManagementException e) {
  309. throw new RuntimeException(e);
  310. } catch (NoSuchAlgorithmException e) {
  311. throw new RuntimeException(e);
  312. }
  313. Registry<ConnectionSocketFactory> registry = registryBuilder.build();
  314. //设置连接管理器
  315. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
  316. connManager.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build());
  317. connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(100000).build());
  318. //构建客户端
  319. return HttpClientBuilder.create().setConnectionManager(connManager).build();
  320. } catch (Exception e) {
  321. e.printStackTrace();
  322. }
  323. return null;
  324. }
  325. private static class AnyTrustStrategy implements TrustStrategy {
  326. @Override
  327. public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  328. return true;
  329. }
  330. }
  331. }
  332. private static CloseableHttpClient getHttpClient() {
  333. return HttpClients.createDefault();
  334. }
  335. private static void closeHttpClient(CloseableHttpClient client) throws IOException {
  336. if (client != null) {
  337. client.close();
  338. }
  339. }
  340. }