All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lone.common.util.HttpUtils Maven / Gradle / Ivy

The newest version!
package com.lone.common.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.lone.common.api.vo.ResultResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 模拟HTTP请求获取返回值
 */
@Slf4j
public class HttpUtils {

	private static PoolingHttpClientConnectionManager connMgr;
	private static RequestConfig requestConfig;
	private static final int MAX_TIMEOUT = 7000;

	static {
		// 设置连接池
		connMgr = new PoolingHttpClientConnectionManager();
		// 设置连接池大小
		connMgr.setMaxTotal(100);
		connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

		RequestConfig.Builder configBuilder = RequestConfig.custom();
		// 设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		// 设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);
		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		// 在提交请求之前 测试连接是否可用
		configBuilder.setStaleConnectionCheckEnabled(true);
		requestConfig = configBuilder.build();
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            url地址
	 * @param param
	 *            请求参数
	 * @param noNeedResponse
	 *            不需要返回结果
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String httpPost(String url, String param, boolean noNeedResponse)
			throws ClientProtocolException, IOException {

		url = URLDecoder.decode(url, "UTF-8");
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = null;
		HttpPost method = new HttpPost(url);

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(300).build();// 设置请求和传输超时时间
		method.setConfig(requestConfig);

		if (null != param) {
			StringEntity entity = new StringEntity(param, "utf-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/x-www-form-urlencoded");
			method.setEntity(entity);
		}

		HttpResponse resultRep = httpClient.execute(method);
		/** 请求发送成功,并得到响应 **/
		if (resultRep.getStatusLine().getStatusCode() == 200) {
			String str = "";
			/** 读取服务器返回过来的json字符串数据 **/
			str = EntityUtils.toString(resultRep.getEntity());
			if (noNeedResponse) {
				return null;
			}
			/** 把json字符串转换成json对象 **/
			// jsonResult = JSONObject.parseObject(str);
			result = str;
		}
		return result;
	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param, String... param1) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			if (param1 != null && param1.length > 0 && !StringUtil.isEmpty(param1[0])) {
				connection.setRequestProperty("Content-Type", param1[0]);
			}
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param, String... param1) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			if (param1 != null && param1.length > 0 && !StringUtil.isEmpty(param1[0])) {
				conn.setRequestProperty("Content-Type", param1[0]);
			}
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost1(String url, String param, String... param1) {
		DataOutputStream out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			if (param1 != null && param1.length > 0 && !StringUtil.isEmpty(param1[0])) {
				conn.setRequestProperty("Content-Type", param1[0]);
			}
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new DataOutputStream(conn.getOutputStream());
			// 发送请求参数
			out.writeChars(param); // 这行是关键我之前写的是 out.write(json.getBytes("UTF-8"));
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static BufferedReader sendGetBR(String url, String param, String... param1) {
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			if (param1 != null && param1.length > 0 && !StringUtil.isEmpty(param1[0])) {
				connection.setRequestProperty("Content-Type", param1[0]);
			}
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
		}
		return in;
	}

	/**
	 * 使用httpclient传输文件
	 */
	public static int sendHttpFile(String filePath, String remoteUrl) {
		int status = 0;
		try {
			PostMethod filePost = new PostMethod(remoteUrl);

			File localFile = new File(filePath);
			FilePart fp = new FilePart("file", localFile);

			// StringPart:普通的文本参数
			StringPart uname = new StringPart("username", "aa");
			StringPart pass = new StringPart("password", "123456");
			Part[] parts = { uname, pass, fp };
			// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
			MultipartRequestEntity mre = new MultipartRequestEntity(parts, filePost.getParams());
			filePost.setRequestEntity(mre);
			HttpClient client = new HttpClient();
			status = client.executeMethod(filePost);
			System.out.println(status + "--------------");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 使用finally块来关闭输入流

		}
		return status;
	}

	/**
	 * 使用httpclient 接收文件
	 */
	public static ResultResponse receiveHttpFile(HttpServletRequest request, String outFilePath) {
		ResultResponse response = new ResultResponse();
		try {
			final int NONE = 0; // 状态码,表示没有特殊操作
			final int DATAHEADER = 1; // 表示下一行要读到报头信息
			// 请求消息实体的总长度(请求消息中除消息头之外的数据长度)
			int totalbytes = request.getContentLength();
			File file; // 上传文件储存在服务器上
			// 容纳请求消息实体的字节数组
			byte[] dataOrigin = new byte[totalbytes];
			// 对于post多个文件的表单,b作为原始数据的副本提供提取文件数据的操作
			byte[] b = new byte[totalbytes];
			// 请求消息类型
			String contentType = request.getContentType();
			String fieldname = ""; // 表单域的名称
			String fieldvalue = ""; // 表单域的值
			String fileFormName = ""; // 上传的文件再表单中的名称
			String fileRealName = ""; // 上传文件的真实名字
			String boundary = ""; // 分界符字符串
			String lastboundary = ""; // 结束分界符字符串
			int fileSize = 0; // 文件长度
			// 容纳表单域的名称/值的哈希表
			Map formfieldsTable = new HashMap();
			// 容纳文件域的名称/文件名的哈希表
			Map filenameTable = new HashMap();
			// 在消息头类型中找到分界符的定义
			int pos = contentType.indexOf("boundary=");
			int pos2;
			if (pos != -1) {
				pos += "boundary=".length();
				boundary = "--" + contentType.substring(pos); // 解析出分界符
				lastboundary = boundary + "--"; // 得到结束分界符
			}
			int state = NONE; // 起始状态为NONE
			// 得到请求消息的数据输入流
			DataInputStream in = new DataInputStream(request.getInputStream());
			in.readFully(dataOrigin); // 根据长度,将消息实体的内容读入字节数组dataOrigin中
			in.close(); // 关闭数据流
			String reqcontent = new String(dataOrigin); // 从字节数组中得到表示实体的字符串
			// 从字符串中得到输出缓冲流
			BufferedReader reqbuf = new BufferedReader(new StringReader(reqcontent));
			// 设置循环标志
			boolean flag = true;
			while (flag == true) {
				String s = reqbuf.readLine();
				if (s == lastboundary || s == null)
					break;
				switch (state) {
				case NONE:
					if (s.startsWith(boundary)) {
						// 如果读到分界符,则表示下一行一个头信息
						state = DATAHEADER;
					}
					break;
				case DATAHEADER:
					pos = s.indexOf("filename=");
					// 先判断出这是一个文本表单域的头信息,还是一个上传文件的头信息
					if (pos == -1) {
						// 如果是文本表单域的头信息,解析出表单域的名称---这个方法中什么都没有做
						state = NONE; // 设置状态码,准备读取表单域的值
					} else {
						// 如果是文件数据的头,先存储这一行,用于在字节数组中定位
						// 这个方法是将文件数据直接进行存盘,下面读取文件数据的基本上是没多大用处的
						String temp = s;
						// 先解析出文件名
						pos = s.indexOf("name=");
						pos += "name=".length() + 1; // 1表示后面的"的占位
						pos2 = s.indexOf("filename=");
						String s1 = s.substring(pos, pos2 - 3); // 3表示";加上一个空格,解析出来的是name的值
						fileFormName = s1;
						pos2 += "filename=".length() + 1; // 1表示后面的"的占位
						s = s.substring(pos2);
						int l = s.length();
						s = s.substring(0, l - 1);// 解析出来的是filename的值
						pos2 = s.lastIndexOf("\\");// 如果filename中有/符号,需要进行的操作
						s = s.substring(pos2 + 1);
						fileRealName = s;
						System.out.println("fileRealName:" + fileRealName);
						if (fileRealName.length() != 0) { // 确定有文件被上传
							s = reqbuf.readLine();
							boolean isContent = true;
							// 循环数据-将请求头的数据过滤掉
							while (isContent) {
								if (s.indexOf("Content") != -1) {
									s = reqbuf.readLine();
								} else {
									isContent = false;
								}
							}
							// 过滤掉请求头下面的空行---每个请求都有的
							s = reqbuf.readLine();

							// 上传文件输出的地址文件
							file = new File(outFilePath + File.separator + fileRealName);
							DataOutputStream fileout = new DataOutputStream(new FileOutputStream(file));
							// 循环写入到输出文件中
							while ((!s.startsWith(boundary)) && (!s.startsWith(lastboundary))) {
								fileout.writeChars(s);
								fileout.writeChars("\r\n");
								s = reqbuf.readLine();
								// 如果读到分解符开始下一次的判断
								if (s.startsWith(boundary)) {
									state = DATAHEADER;
									break;
								}
							}
						}
					}
					// 结束switch
					break;
				}
			}
			response.isSuccess("操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			response.isFailed("操作失败!", "");
			response.setSuccess(false);
		} finally {
			// 使用finally块来关闭输入流

		}
		return response;
	}

	/**
	 * 发送 GET 请求(HTTP),不带输入数据
	 * 
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		return doGet(url, new HashMap());
	}

	/**
	 * 发送 GET 请求(HTTP),K-V形式
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doGet(String url, Map params) {
		String apiUrl = url;
		StringBuffer param = new StringBuffer();
		int i = 0;
		for (String key : params.keySet()) {
			if (i == 0)
				param.append("?");
			else
				param.append("&");
			param.append(key).append("=").append(params.get(key));
			i++;
		}
		apiUrl += param;
		String result = null;
		org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpGet httpPost = new HttpGet(apiUrl);
			HttpResponse response = httpclient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();

			System.out.println("执行状态码 : " + statusCode);

			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				result = IOUtils.toString(instream, "UTF-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 发送 POST 请求(HTTP),不带输入数据
	 * 
	 * @param apiUrl
	 * @return
	 */
	public static String doPost(String apiUrl) {
		return doPost(apiUrl, new HashMap());
	}

	/**
	 * 发送 POST 请求(HTTP),K-V形式
	 * 
	 * @param apiUrl
	 *            API接口URL
	 * @param params
	 *            参数map
	 * @return
	 */
	public static String doPost(String apiUrl, Map params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			httpPost.setConfig(requestConfig);
			List pairList = new ArrayList(params.size());
			for (Map.Entry entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			System.out.println(response.toString());
			HttpEntity entity = response.getEntity();
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 POST 请求(HTTP),JSON形式
	 * 
	 * @param apiUrl
	 * @param json
	 *            json对象
	 * @return
	 */
	public static String doPost(String apiUrl, Object json) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			System.out.println(response.getStatusLine().getStatusCode());
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 SSL POST 请求(HTTPS),K-V形式
	 * 
	 * @param apiUrl
	 *            API接口URL
	 * @param params
	 *            参数map
	 * @return
	 */
	public static String doPostSSL(String apiUrl, Map params) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			List pairList = new ArrayList(params.size());
			for (Map.Entry entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 SSL POST 请求(HTTPS),JSON形式
	 * 
	 * @param apiUrl
	 *            API接口URL
	 * @param json
	 *            JSON对象
	 * @return
	 */
	public static String doPostSSL(String apiUrl, Object json) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 创建SSL安全连接
	 *
	 * @return
	 */
	private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
		SSLConnectionSocketFactory sslsf = null;
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}

				@Override
				public void verify(String host, SSLSocket ssl) throws IOException {
				}

				@Override
				public void verify(String host, X509Certificate cert) throws SSLException {
				}

				@Override
				public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
				}
			});
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		return sslsf;
	}

	public static HostnameVerifier hv = new HostnameVerifier() {
		public boolean verify(String urlHostName, SSLSession session) {
			System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
			return true;
		}
	};

	public static void trustAllHttpsCertificates() throws Exception {
		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	}

	static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy