HttpUtil.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package com.lightinit.hsdataplatformresdir.common;
  2. import com.google.gson.Gson;
  3. import com.lightinit.hsdataplatformresdir.common.ssl.MySecureProtocolSocketFactory;
  4. import com.lightinit.hsdataplatformresdir.dictionary.DicGitToken;
  5. import org.apache.commons.httpclient.methods.PostMethod;
  6. import org.apache.commons.httpclient.methods.PutMethod;
  7. import org.apache.commons.httpclient.methods.RequestEntity;
  8. import org.apache.commons.httpclient.methods.StringRequestEntity;
  9. import org.apache.commons.httpclient.protocol.Protocol;
  10. import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
  11. import org.apache.http.client.methods.CloseableHttpResponse;
  12. import org.apache.http.client.methods.HttpGet;
  13. import org.apache.http.client.utils.URIBuilder;
  14. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.ssl.SSLContexts;
  18. import org.apache.http.ssl.TrustStrategy;
  19. import org.apache.http.util.EntityUtils;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import javax.net.ssl.SSLContext;
  23. import javax.net.ssl.TrustManager;
  24. import javax.net.ssl.X509TrustManager;
  25. import java.io.IOException;
  26. import java.net.URI;
  27. import java.security.KeyManagementException;
  28. import java.security.NoSuchAlgorithmException;
  29. import java.security.cert.CertificateException;
  30. import java.security.cert.X509Certificate;
  31. import java.util.*;
  32. public class HttpUtil {
  33. private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
  34. /**
  35. * @describe: TODO 服务于6.0接口
  36. * @param url 访问地址
  37. * @param head 请求头
  38. * @param req 请求体内容
  39. **/
  40. public static String httpPost(String url, Map<String,String> head,Map<String,?> req) throws Exception{
  41. //声明
  42. ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
  43. //加入相关的https请求方式
  44. Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
  45. //发送请求即可
  46. org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
  47. Gson gson = new Gson();
  48. PostMethod post = new PostMethod(url);
  49. String str = gson.toJson(req);
  50. gson.fromJson(str,Map.class) ;
  51. RequestEntity re = new StringRequestEntity(str,"application/json","utf-8");
  52. if(head!=null){
  53. Set<Map.Entry<String,String>> headSet = head.entrySet();
  54. for (Map.Entry<String, String> entry : headSet) {
  55. post.setRequestHeader(entry.getKey(),entry.getValue());
  56. }
  57. }
  58. post.setRequestEntity(re);
  59. int status = client.executeMethod(post);
  60. System.out.println("=================status:"+status);
  61. if(status!=200){
  62. //抛出异常
  63. byte[] bytes = post.getResponseBody();
  64. String content = new String(bytes,"UTF-8");
  65. System.out.println(content);
  66. }
  67. String content = post.getResponseBodyAsString();
  68. System.out.println("Access System authenticate, Response: " + content);
  69. return content;
  70. }
  71. public static String httpPut(String url, Map<String,String> head,Map<String,?> req) throws Exception{
  72. //声明
  73. ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
  74. //加入相关的https请求方式
  75. Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
  76. //发送请求即可
  77. org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
  78. Gson gson = new Gson();
  79. PutMethod post = new PutMethod(url);
  80. String str = gson.toJson(req);
  81. gson.fromJson(str,Map.class) ;
  82. RequestEntity re = new StringRequestEntity(str,"application/json","utf-8");
  83. if(head!=null){
  84. Set<Map.Entry<String,String>> headSet = head.entrySet();
  85. for (Map.Entry<String, String> entry : headSet) {
  86. post.setRequestHeader(entry.getKey(),entry.getValue());
  87. }
  88. }
  89. post.setRequestEntity(re);
  90. int status = client.executeMethod(post);
  91. System.out.println("=================status:"+status);
  92. if(status!=200){
  93. //抛出异常
  94. byte[] bytes = post.getResponseBody();
  95. String content = new String(bytes,"UTF-8");
  96. System.out.println(content);
  97. }
  98. String content = post.getResponseBodyAsString();
  99. System.out.println("Access System authenticate, Response: " + content);
  100. return content;
  101. }
  102. /**
  103. * @describe: TODO 服务于5.0接口
  104. * @param url 请求路径
  105. * @param head 请求头
  106. * @param req 请求体内容
  107. **/
  108. public static String httpPost2(String url, Map<String,String> head,Map<String,?> req) throws Exception{
  109. //声明
  110. ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
  111. //加入相关的https请求方式
  112. Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
  113. //发送请求即可
  114. org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
  115. Map<String,Object> strMap = new HashMap();
  116. Gson gson = new Gson();
  117. PostMethod post = new PostMethod(url);
  118. strMap.put("head",head);
  119. strMap.put("body",req);
  120. String str = gson.toJson(strMap);
  121. RequestEntity re = new StringRequestEntity(str,"application/json","utf-8");
  122. post.setRequestEntity(re);
  123. int status = client.executeMethod(post);
  124. System.out.println("Access System authenticate, Status: " + post.getStatusCode());
  125. System.out.println("Access System authenticate, Response: " + post.getResponseBodyAsString());
  126. String content = post.getResponseBodyAsString();
  127. return content;
  128. }
  129. public static String httpGet(String url,String accessticket,Map<String,?> param) throws Exception {
  130. //CloseableHttpClient httpclient = HttpClients.createDefault();
  131. CloseableHttpClient httpclient = getIgnoeSSLClient();
  132. String resultString = "";
  133. CloseableHttpResponse response = null;
  134. try {
  135. // 创建uri
  136. URIBuilder builder = new URIBuilder(url);
  137. if (param != null) {
  138. for (String key : param.keySet()) {
  139. builder.addParameter(key, (String)param.get(key));
  140. }
  141. }
  142. URI uri = builder.build();
  143. // 创建http GET请求
  144. HttpGet httpGet = new HttpGet(uri);
  145. if (accessticket!=null) httpGet.addHeader("accessticket",accessticket);
  146. // 执行请求
  147. response = httpclient.execute(httpGet);
  148. // 判断返回状态是否为200
  149. logger.info("访问的路径为:"+url+"状态为:"+response.getStatusLine().getStatusCode());
  150. if (response.getStatusLine().getStatusCode() == 200) {
  151. byte[] bytes= EntityUtils.toByteArray(response.getEntity());
  152. resultString = new String(bytes);
  153. //resultString = EntityUtils.toString(response.getEntity(), "ISO-8859-1");
  154. //resultString= Base64.encodeBase64String(bytes);
  155. }
  156. } catch (Exception e) {
  157. e.printStackTrace();
  158. } finally {
  159. try {
  160. if (response != null) {
  161. response.close();
  162. }
  163. httpclient.close();
  164. } catch (IOException e) {
  165. e.printStackTrace();
  166. }
  167. }
  168. logger.info("查询的结果:"+resultString);
  169. return resultString;
  170. }
  171. public static String httpGet2(String url,String accessticket,Map<String,?> param) throws Exception {
  172. //CloseableHttpClient httpclient = HttpClients.createDefault();
  173. CloseableHttpClient httpclient = getIgnoeSSLClient();
  174. String resultString = "";
  175. CloseableHttpResponse response = null;
  176. try {
  177. // 创建uri
  178. URIBuilder builder = new URIBuilder(url);
  179. if (param != null) {
  180. for (String key : param.keySet()) {
  181. builder.addParameter(key, (String)param.get(key));
  182. }
  183. }
  184. URI uri = builder.build();
  185. // 创建http GET请求
  186. HttpGet httpGet = new HttpGet(uri);
  187. if (accessticket!=null) httpGet.addHeader("Authorization",accessticket);
  188. // 执行请求
  189. response = httpclient.execute(httpGet);
  190. // 判断返回状态是否为200
  191. logger.info("访问的路径为:"+url+"状态为:"+response.getStatusLine().getStatusCode());
  192. if (response.getStatusLine().getStatusCode() == 200) {
  193. byte[] bytes= EntityUtils.toByteArray(response.getEntity());
  194. resultString = new String(bytes);
  195. //resultString = EntityUtils.toString(response.getEntity(), "ISO-8859-1");
  196. //resultString= Base64.encodeBase64String(bytes);
  197. }
  198. } catch (Exception e) {
  199. e.printStackTrace();
  200. } finally {
  201. try {
  202. if (response != null) {
  203. response.close();
  204. }
  205. httpclient.close();
  206. } catch (IOException e) {
  207. e.printStackTrace();
  208. }
  209. }
  210. logger.info("查询的结果:"+resultString);
  211. return resultString;
  212. }
  213. public static String httpGet(String url,Map<String,Object> params) throws Exception {
  214. return httpGet(url,null,params);
  215. }
  216. public static String httpGet(String url,String accessticket) throws Exception {
  217. return httpGet(url,accessticket,null);
  218. }
  219. public static Map<String,Object> strToMap(String message){
  220. Gson gson = new Gson();
  221. Map<String,Object> map = new HashMap<String, Object>();
  222. map = gson.fromJson(message,map.getClass());
  223. return map;
  224. }
  225. public static List<Object> strToList(String message){
  226. Gson gson = new Gson();
  227. List<Object> list = new ArrayList<>();
  228. list = gson.fromJson(message,list.getClass());
  229. return list;
  230. }
  231. public static Map<String,String> getHead(String appid,String appkey){
  232. Map<String,String> head = new HashMap<String,String>();
  233. head.put("appid",appid);
  234. head.put("appkey",appkey);
  235. return head;
  236. }
  237. public static String getToken(String url, Map<String,String> head,String contentType) throws Exception{
  238. //声明
  239. ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
  240. //加入相关的https请求方式
  241. Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
  242. //发送请求即可
  243. org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
  244. // HttpClient client = new HttpClient();
  245. PostMethod post = new PostMethod(url);
  246. String str = DicGitToken.PARAMS ;
  247. RequestEntity re = new StringRequestEntity(str,contentType,"utf-8");
  248. if(head!=null){
  249. Set<Map.Entry<String,String>> headSet = head.entrySet();
  250. for (Map.Entry<String, String> entry : headSet) {
  251. post.setRequestHeader(entry.getKey(),entry.getValue());
  252. }
  253. }
  254. post.setRequestEntity(re);
  255. int status = client.executeMethod(post);
  256. System.out.println("=================status:"+status);
  257. if(status!=200){
  258. //抛出异常
  259. byte[] bytes = post.getResponseBody();
  260. String content = new String(bytes,"UTF-8");
  261. System.out.println(content);
  262. }
  263. String content = post.getResponseBodyAsString();
  264. System.out.println("Access System authenticate, Response: " + content);
  265. return content;
  266. }
  267. /**
  268. * 绕过验证
  269. *
  270. * @return
  271. * @throws NoSuchAlgorithmException
  272. * @throws KeyManagementException
  273. */
  274. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  275. SSLContext sc = SSLContext.getInstance("SSLv3");
  276. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  277. X509TrustManager trustManager = new X509TrustManager() {
  278. @Override
  279. public void checkClientTrusted(
  280. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  281. String paramString) throws CertificateException {
  282. }
  283. @Override
  284. public void checkServerTrusted(
  285. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  286. String paramString) throws CertificateException {
  287. }
  288. @Override
  289. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  290. return null;
  291. }
  292. };
  293. sc.init(null, new TrustManager[] { trustManager }, null);
  294. return sc;
  295. }
  296. /**
  297. * 获取忽略证书验证的client
  298. *
  299. * @return
  300. * @throws Exception
  301. */
  302. public static CloseableHttpClient getIgnoeSSLClient() throws Exception {
  303. SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
  304. @Override
  305. public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  306. return true;
  307. }
  308. }).build();
  309. //创建httpClient
  310. CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
  311. setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
  312. return client;
  313. }
  314. }