HttpClientUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 java.io.IOException;
  36. import java.io.InputStream;
  37. import java.io.InputStreamReader;
  38. import java.io.UnsupportedEncodingException;
  39. import java.nio.charset.Charset;
  40. import java.security.KeyManagementException;
  41. import java.security.KeyStore;
  42. import java.security.KeyStoreException;
  43. import java.security.NoSuchAlgorithmException;
  44. import java.security.cert.CertificateException;
  45. import java.security.cert.X509Certificate;
  46. import java.util.HashMap;
  47. import java.util.List;
  48. import java.util.Map;
  49. import java.util.logging.Logger;
  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. * post 键值对
  179. *
  180. * @param url
  181. * @param data 键值对内容
  182. * @return
  183. */
  184. public static String sentData(String url, String data) {
  185. if(!StringUtils.isEmpty(url)&&!StringUtils.isEmpty(data)){
  186. String result = sendPost(data, url);
  187. return result;
  188. }
  189. return "400";
  190. }
  191. /**
  192. * post 键值对
  193. *
  194. * @param url
  195. * @param data 键值对内容
  196. * @return
  197. */
  198. public static String postKeyValue(String url, List<BasicNameValuePair> data) {
  199. CloseableHttpClient httpClient = getHttpClient();
  200. try {
  201. HttpPost post = new HttpPost(url);
  202. //url格式编码
  203. UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(data, "UTF-8");
  204. post.setEntity(uefEntity);
  205. CloseableHttpResponse httpResponse = httpClient.execute(post);
  206. HttpEntity entity = httpResponse.getEntity();
  207. try {
  208. if (null != entity) {
  209. String result = EntityUtils.toString(entity);
  210. return result;
  211. }
  212. } finally {
  213. httpResponse.close();
  214. }
  215. } catch (UnsupportedEncodingException e) {
  216. e.printStackTrace();
  217. } catch (ClientProtocolException e) {
  218. e.printStackTrace();
  219. } catch (IOException e) {
  220. e.printStackTrace();
  221. } finally {
  222. try {
  223. closeHttpClient(httpClient);
  224. } catch (IOException e) {
  225. e.printStackTrace();
  226. }
  227. }
  228. return null;
  229. }
  230. /**
  231. * get json
  232. *
  233. * @param url
  234. * @return
  235. */
  236. public static JSONObject get(String url) throws IOException {
  237. HttpClient client = HttpClientBuilder.create().build();
  238. client = WebClientDevWrapper.wrapClient(client);
  239. HttpGet get = new HttpGet(url);
  240. JSONObject response = null;
  241. InputStream instream = null;
  242. try {
  243. HttpResponse res = null;
  244. if (client != null) {
  245. res = client.execute(get);
  246. }
  247. if (res != null && res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  248. HttpEntity entity = res.getEntity();
  249. instream = entity.getContent();
  250. response = new JSONObject(new JSONTokener(new InputStreamReader(instream, "utf-8")));
  251. }
  252. } catch (Exception e) {
  253. throw new RuntimeException(e);
  254. } finally {
  255. if (instream != null) {
  256. instream.close();
  257. }
  258. }
  259. return response;
  260. }
  261. private static class WebClientDevWrapper {
  262. public static HttpClient wrapClient(HttpClient base) {
  263. try {
  264. RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  265. ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
  266. registryBuilder.register("http", plainSF);
  267. //指定信任密钥存储对象和连接套接字工厂
  268. try {
  269. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  270. SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
  271. LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  272. registryBuilder.register("https", sslSF);
  273. } catch (KeyStoreException e) {
  274. throw new RuntimeException(e);
  275. } catch (KeyManagementException e) {
  276. throw new RuntimeException(e);
  277. } catch (NoSuchAlgorithmException e) {
  278. throw new RuntimeException(e);
  279. }
  280. Registry<ConnectionSocketFactory> registry = registryBuilder.build();
  281. //设置连接管理器
  282. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
  283. connManager.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build());
  284. connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(100000).build());
  285. //构建客户端
  286. return HttpClientBuilder.create().setConnectionManager(connManager).build();
  287. } catch (Exception e) {
  288. e.printStackTrace();
  289. }
  290. return null;
  291. }
  292. private static class AnyTrustStrategy implements TrustStrategy {
  293. @Override
  294. public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  295. return true;
  296. }
  297. }
  298. }
  299. private static CloseableHttpClient getHttpClient() {
  300. return HttpClients.createDefault();
  301. }
  302. private static void closeHttpClient(CloseableHttpClient client) throws IOException {
  303. if (client != null) {
  304. client.close();
  305. }
  306. }
  307. }