package com.lightinit.hsdataplatformresdir.common; import com.google.gson.Gson; import com.lightinit.hsdataplatformresdir.common.ssl.MySecureProtocolSocketFactory; import com.lightinit.hsdataplatformresdir.dictionary.DicGitToken; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.*; public class HttpUtil { private static Logger logger = LoggerFactory.getLogger(HttpUtil.class); /** * @describe: TODO 服务于6.0接口 * @param url 访问地址 * @param head 请求头 * @param req 请求体内容 **/ public static String httpPost(String url, Map head,Map req) throws Exception{ //声明 ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); //加入相关的https请求方式 Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); //发送请求即可 org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); Gson gson = new Gson(); PostMethod post = new PostMethod(url); String str = gson.toJson(req); gson.fromJson(str,Map.class) ; RequestEntity re = new StringRequestEntity(str,"application/json","utf-8"); if(head!=null){ Set> headSet = head.entrySet(); for (Map.Entry entry : headSet) { post.setRequestHeader(entry.getKey(),entry.getValue()); } } post.setRequestEntity(re); int status = client.executeMethod(post); System.out.println("=================status:"+status); if(status!=200){ //抛出异常 byte[] bytes = post.getResponseBody(); String content = new String(bytes,"UTF-8"); System.out.println(content); } String content = post.getResponseBodyAsString(); System.out.println("Access System authenticate, Response: " + content); return content; } public static String httpPut(String url, Map head,Map req) throws Exception{ //声明 ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); //加入相关的https请求方式 Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); //发送请求即可 org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); Gson gson = new Gson(); PutMethod post = new PutMethod(url); String str = gson.toJson(req); gson.fromJson(str,Map.class) ; RequestEntity re = new StringRequestEntity(str,"application/json","utf-8"); if(head!=null){ Set> headSet = head.entrySet(); for (Map.Entry entry : headSet) { post.setRequestHeader(entry.getKey(),entry.getValue()); } } post.setRequestEntity(re); int status = client.executeMethod(post); System.out.println("=================status:"+status); if(status!=200){ //抛出异常 byte[] bytes = post.getResponseBody(); String content = new String(bytes,"UTF-8"); System.out.println(content); } String content = post.getResponseBodyAsString(); System.out.println("Access System authenticate, Response: " + content); return content; } /** * @describe: TODO 服务于5.0接口 * @param url 请求路径 * @param head 请求头 * @param req 请求体内容 **/ public static String httpPost2(String url, Map head,Map req) throws Exception{ //声明 ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); //加入相关的https请求方式 Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); //发送请求即可 org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); Map strMap = new HashMap(); Gson gson = new Gson(); PostMethod post = new PostMethod(url); strMap.put("head",head); strMap.put("body",req); String str = gson.toJson(strMap); RequestEntity re = new StringRequestEntity(str,"application/json","utf-8"); post.setRequestEntity(re); int status = client.executeMethod(post); System.out.println("Access System authenticate, Status: " + post.getStatusCode()); System.out.println("Access System authenticate, Response: " + post.getResponseBodyAsString()); String content = post.getResponseBodyAsString(); return content; } public static String httpGet(String url,String accessticket,Map param) throws Exception { //CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = getIgnoeSSLClient(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, (String)param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); if (accessticket!=null) httpGet.addHeader("accessticket",accessticket); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 logger.info("访问的路径为:"+url+"状态为:"+response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == 200) { byte[] bytes= EntityUtils.toByteArray(response.getEntity()); resultString = new String(bytes); //resultString = EntityUtils.toString(response.getEntity(), "ISO-8859-1"); //resultString= Base64.encodeBase64String(bytes); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } logger.info("查询的结果:"+resultString); return resultString; } public static String httpGet2(String url,String accessticket,Map param) throws Exception { //CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = getIgnoeSSLClient(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, (String)param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); if (accessticket!=null) httpGet.addHeader("Authorization",accessticket); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 logger.info("访问的路径为:"+url+"状态为:"+response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == 200) { byte[] bytes= EntityUtils.toByteArray(response.getEntity()); resultString = new String(bytes); //resultString = EntityUtils.toString(response.getEntity(), "ISO-8859-1"); //resultString= Base64.encodeBase64String(bytes); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } logger.info("查询的结果:"+resultString); return resultString; } public static String httpGet(String url,Map params) throws Exception { return httpGet(url,null,params); } public static String httpGet(String url,String accessticket) throws Exception { return httpGet(url,accessticket,null); } public static Map strToMap(String message){ Gson gson = new Gson(); Map map = new HashMap(); map = gson.fromJson(message,map.getClass()); return map; } public static List strToList(String message){ Gson gson = new Gson(); List list = new ArrayList<>(); list = gson.fromJson(message,list.getClass()); return list; } public static Map getHead(String appid,String appkey){ Map head = new HashMap(); head.put("appid",appid); head.put("appkey",appkey); return head; } public static String getToken(String url, Map head,String contentType) throws Exception{ //声明 ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); //加入相关的https请求方式 Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); //发送请求即可 org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); // HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); String str = DicGitToken.PARAMS ; RequestEntity re = new StringRequestEntity(str,contentType,"utf-8"); if(head!=null){ Set> headSet = head.entrySet(); for (Map.Entry entry : headSet) { post.setRequestHeader(entry.getKey(),entry.getValue()); } } post.setRequestEntity(re); int status = client.executeMethod(post); System.out.println("=================status:"+status); if(status!=200){ //抛出异常 byte[] bytes = post.getResponseBody(); String content = new String(bytes,"UTF-8"); System.out.println(content); } String content = post.getResponseBodyAsString(); System.out.println("Access System authenticate, Response: " + content); return content; } /** * 绕过验证 * * @return * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sc = SSLContext.getInstance("SSLv3"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; sc.init(null, new TrustManager[] { trustManager }, null); return sc; } /** * 获取忽略证书验证的client * * @return * @throws Exception */ public static CloseableHttpClient getIgnoeSSLClient() throws Exception { SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }).build(); //创建httpClient CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext). setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); return client; } }