HttpsUtil 跳过ssl认证公用方法(兼容骨灰项目低版本)

HttpsUtil 跳过ssl认证公用方法(兼容骨灰项目低版本)


import java.io.BufferedReader;
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.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.rmi.ConnectException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import org.dom4j.DocumentException;

import com.payment.entity.LogEntity;

import net.sf.json.JSONObject;

public class HttpsUtils1 {
	private static final  LogEntity logger = new LogEntity("ott_payment");
	static ThreadLocal<Integer> tLocal = new ThreadLocal<>();
	static int MAX_REQUEST = 0;
	
	private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        @Override
		public boolean verify(String s, SSLSession sslsession) {
            System.out.println("WARNING: Hostname is not matched for cert.");
            return true;
        }
    };
    
    public static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
		public boolean verify(String hostname, SSLSession session) {
            return true;// 直接返回true
        }
    }
    
    public static class MyX509TrustManager implements X509TrustManager {  
    	  
        @Override
    	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
        }  
      
        @Override
    	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
        }  
      
        @Override
    	public X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
    }  
    
    
    public static void download(String urlStr, File file) {
    	URL url = null;
		HttpURLConnection connection = null;
        try {
        	url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.connect();
			InputStream is = connection.getInputStream();
			byte[] buffer = new byte[8*1024];
            file.getParentFile().mkdirs();
            FileOutputStream fileout = new FileOutputStream(file);
            int len;
            try {
				while ((len = is.read(buffer))!=-1) {
					fileout.write(buffer, 0, len);
				}
				fileout.flush();
				fileout.getFD().sync();
			} finally {
				if(fileout!=null){
					fileout.close();
				}
				if(is!=null){
					is.close();
				}
			}

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	/**
	 * 模拟get请求
	 * @param urlStr 请求的url
	 * @return
	 */
	public static String getResult(String urlStr,String charset) {
		URL url = null;
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		try {
			//建立连接
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.connect();
			//获得返回结果
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null!=reader){
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}
	
	public static String getResultNotReTry(String urlStr,String charset) {
		URL url = null;
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		try {
			//建立连接
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.connect();
			//获得返回结果
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			return buffer.toString();
		} catch (IOException e) {
			if (e.getMessage().contains("Read timed out")) {
				MAX_REQUEST++;
				if (MAX_REQUEST <= 3) {
					System.out.println("Try to connect again: " + MAX_REQUEST);
					getResult(urlStr,charset);
				}
				MAX_REQUEST = 0;
			}
			e.printStackTrace();
		} finally {
			if(null!=reader){
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}
	
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String urlNameString) {
		long start = System.currentTimeMillis();
		logger.warn("---sendGet:"+urlNameString);
		StringBuffer result = new StringBuffer("");
		BufferedReader in = null;
		HttpURLConnection connection = null;
		try {
			// URLEncoder.encode(urlNameString, "utf-8")
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			connection = (HttpURLConnection) realUrl.openConnection();
			// 建立实际的连接
			connection.connect();
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
				if (connection != null) {
					connection.disconnect();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		logger.warn("---sendGet costs:"+(System.currentTimeMillis()-start));
		return result.toString();
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		long start = System.currentTimeMillis();
		logger.warn("---sendPost:"+url);
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuffer result = new StringBuffer("");
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection)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)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}

		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		logger.warn("---sendPost costs:"+(System.currentTimeMillis()-start));
		return result.toString();
	}
	
	public static String doPost2(String url, String param) {
		long start = System.currentTimeMillis();
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuffer result = new StringBuffer();
		try {
			URL realUrl = new 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)");
			conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			conn.connect();
			InputStream is=conn.getInputStream();
			in = new BufferedReader(new InputStreamReader(is, "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}

		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		logger.warn("---doPost {}?{}"+ url+ param);
		//logger.warn("---result:{}"+ result.toString().length()>500 ? result.toString().substring(0, 500) : result.toString());
		//logger.warn("---costs:{}", (System.currentTimeMillis() - start));
		return result.toString();
	}

	public static String doJsonPost(String jsonInfo, String URL) {
		long start = System.currentTimeMillis();
		logger.warn("---doJsonPost:"+URL);
		byte[] xmlData = jsonInfo.getBytes();
		BufferedReader in = null;
		DataOutputStream printout = null;
		StringBuffer result = new StringBuffer("");
		try {
			URL url = new URL(URL);
			URLConnection urlCon = url.openConnection();
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setUseCaches(false);
			urlCon.setRequestProperty("Content-Type", "text/xml");
			urlCon.setRequestProperty("Content-length",
					String.valueOf(xmlData.length));
			printout = new DataOutputStream(urlCon.getOutputStream());
			printout.write(xmlData);
			printout.flush();
			in = new BufferedReader(new InputStreamReader(
					urlCon.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (printout != null) {
					printout.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		logger.warn("---result:"+result.toString());
		logger.warn("---doJsonPost costs:"+(System.currentTimeMillis()-start));
		return result.toString();
	}

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式(GET、POST)
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		long start = System.currentTimeMillis();
		logger.warn("---httpRequest:"+requestUrl);
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			System.out.println(buffer.toString());
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.warn("---httpRequest costs:"+(System.currentTimeMillis()-start));
		return jsonObject;
	}
	
	public static String httpsRequest(String requestUrl,
			String requestMethod, String outputStr) {
		long start = System.currentTimeMillis();
		logger.warn("---httpRequest:"+requestUrl);
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置文件字符集:
			httpUrlConn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			String responseMessage = httpUrlConn.getResponseMessage();
			int responseCode = httpUrlConn.getResponseCode();
			System.out.println("responseMessage:"+responseMessage);
			System.out.println("responseCode:"+responseCode);
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			String result = buffer.toString();
//			System.out.println(result);
			return result;
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.warn("---httpRequest costs:"+(System.currentTimeMillis()-start));
		return "";
	}
	
	public static String postMap(String url, Map<String, String> param) {
		StringBuffer buffer = new StringBuffer();
		for (Entry<String, String> entry : param.entrySet()) {
			buffer.append("&").append(entry.getKey())
					.append("=").append(entry.getValue());
		}
		return sendPost(url, buffer.toString());
	}
	

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值