使用HttpURLConnection发送http请求,发送信任所有证书形式的https请求,发送校验服务端证书的https请求

一、发送请求http请求
package com.ykq;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 发送https请求
 *
 * @author YKQ
 */
public class SendHttpUtil {
	
	public static String sendHttp(String method, String urlStr,
	 String paramStr, Map<String, String> requestProperty) {
		OutputStream os = null;
		InputStream is = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpConnection = null;
		try {
			// 这个地方一定要返回,而不是当成对象传入设置即可
			httpConnection = getHttpConnect(httpConnection, urlStr,
			 method, requestProperty);
			// 开始连接
			httpConnection.connect();
			// 获取返回报文
			String respStr = getRespStr(httpConnection, paramStr,
			 os, is, bis);
			return respStr;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭输入输出流,关闭链接
			closeStreamAndConnect(os, is, bis, httpConnection);
		}
		return "";
	}
	
	/**
	 * 获取链接
	 * @throws Exception 
	 */
	private static HttpURLConnection getHttpConnect(
		HttpURLConnection httpConnection, String urlStr,
		String method, Map<String, String> requestProperty)
		 throws Exception {
		try {
			// 获取URL地址
			URL url = new URL(urlStr);
			// 获取URL链接
			httpConnection = (HttpURLConnection) url.openConnection();
			// 设置超时时间
			httpConnection.setConnectTimeout(3000);
			httpConnection.setReadTimeout(3000);
			// 设置请求方式POST/GET/PUT/DELETE
			httpConnection.setRequestMethod(method);
			// 不使用缓存
			httpConnection.setUseCaches(false);
			// 允许输入
			httpConnection.setDoInput(true);
			// 允许输出
			httpConnection.setDoOutput(true);
			// 例如设置请求头为json请求,也可以设置其他请求头
			//httpConnection.setRequestProperty("Content-Type",
	           //	  "application/json;charset=utf-8");
			if(requestProperty != null && !requestProperty.isEmpty()) {
				// 遍历map
				Set<Entry<String, String>> propertyEntry
					= requestProperty.entrySet();
				Iterator<Entry<String, String>> iterator
					= propertyEntry.iterator();
				Entry<String, String> entry = null;
				while (iterator.hasNext()) {
					entry = iterator.next();
					httpConnection.setRequestProperty(entry.getKey(),
							entry.getValue());
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return httpConnection;
	}
	
	/**
	 * 获取响应体
	 * @throws Exception 
	 */
	private static String getRespStr(HttpURLConnection httpConnection,
	 String paramStr, OutputStream os, InputStream is, 
	  BufferedInputStream bis) throws Exception {
		StringBuffer respBuffer = new StringBuffer();
		try {
			// 如果参数不为空
			if (paramStr != null && !paramStr.isEmpty()) {
				// 从连接获取输出流
				os = httpConnection.getOutputStream();
				// 开始写
				byte[] b = paramStr.getBytes("UTF-8");
				os.write(b, 0, b.length);
			}
			// 如果返回code等于200,接收返回报文
			if (HttpURLConnection.HTTP_OK
					== httpConnection.getResponseCode()) {
				// 得到输入流
				is = httpConnection.getInputStream();
				bis = new BufferedInputStream(is);
				byte[] respByte = new byte[1024];
				while(bis.read(respByte) > 0) {
					// 这个地方注意,字节数组使用new String即可转为字符串
					// toString() 和 Arrays.toString()都不行
					respBuffer.append(new String(respByte, "UTF-8"));
				}
			}
		} catch(Exception e) {
			throw e;
		}
		return respBuffer.toString();
	}
	
	/**
	 * 关闭流和连接
	 */
	private static void closeStreamAndConnect(OutputStream os,
	 InputStream is, BufferedInputStream bis,
	  	HttpURLConnection connection) {
		try {
			connection.disconnect();
		} catch(Exception e) {
		}
		try {
			if (is != null) {
				is.close();
			}
		} catch(Exception e) {
		}
		try {
			if (bis != null) {
				bis.close();
			}
		} catch(Exception e) {
		}
		try {
			if (os != null) {
				os.close();
			}
		} catch(Exception e) {
		}
	}
}
二、发送https请求——信任所有证书
package com.ykq;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * 发送https请求
 *
 * @author YKQ
 */
public class SendHttpsUtil {
    /**
     * 设置不验证主机
     */
    private static final HostnameVerifier DO_NOT_VERIFY
     = new HostnameVerifier() {
        /**
         * 返回恒定为true
         */
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    
    /**
     * 设置为信任所有证书
     */
    static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[] {
        	new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
             String authType) throws CertificateException {
                return;
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain,
             String authType) throws CertificateException {
                return;
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }};
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
    	HttpsURLConnection
    		.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
	
	public static String sendHttps(String method, String urlStr,
	 String paramStr, Map<String, String> requestProperty) {
		OutputStream os = null;
		InputStream is = null;
		BufferedInputStream bis = null;
		HttpsURLConnection httpsConnection = null;
		try {
			// 信任所有证书
			trustAllHttpsCertificates();
			// 这个地方一定要返回,而不是当成对象传入设置即可
			httpsConnection = getHttpConnect(httpsConnection, urlStr,
			 method, requestProperty);
			// 开始连接
			httpsConnection.connect();
			// 获取返回报文
			String respStr = getRespStr(httpsConnection, paramStr,
			 os, is, bis);
			return respStr;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭输入输出流,关闭链接
			closeStreamAndConnect(os, is, bis, httpsConnection);
		}
		return "";
	}
	
	/**
	 * 获取链接
	 * @throws Exception 
	 */
	private static HttpsURLConnection getHttpConnect(
	HttpsURLConnection httpsConnection, String urlStr, String method,
	 Map<String, String> requestProperty) throws Exception {
		try {
			// 获取URL地址
			URL url = new URL(urlStr);
			// 获取URL链接
			httpsConnection = (HttpsURLConnection) url.openConnection();
			// 设置为不校验主机
			httpsConnection.setHostnameVerifier(DO_NOT_VERIFY);
			// 设置超时时间
			httpsConnection.setConnectTimeout(3000);
			httpsConnection.setReadTimeout(3000);
			// 设置请求方式POST/GET/PUT/DELETE
			httpsConnection.setRequestMethod(method);
			// 不使用缓存
			httpsConnection.setUseCaches(false);
			// 允许输入
			httpsConnection.setDoInput(true);
			// 允许输出
			httpsConnection.setDoOutput(true);
			// 例如设置请求头为json请求,也可以设置其他请求头
			//httpConnection.setRequestProperty("Content-Type",
	           //	  "application/json;charset=utf-8");
			if(requestProperty != null && !requestProperty.isEmpty()) {
				// 遍历map
				Set<Entry<String, String>> propertyEntry
					= requestProperty.entrySet();
				Iterator<Entry<String, String>> iterator
					= propertyEntry.iterator();
				Entry<String, String> entry = null;
				while (iterator.hasNext()) {
					entry = iterator.next();
					httpsConnection.setRequestProperty(entry.getKey(),
							entry.getValue());
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return httpsConnection;
	}
	
	/**
	 * 获取响应体
	 * @throws Exception 
	 */
	private static String getRespStr(
	 HttpsURLConnection httpsConnection, String paramStr,
	 OutputStream os, InputStream is, BufferedInputStream bis)
	  throws Exception {
		StringBuffer respBuffer = new StringBuffer();
		try {
			// 如果参数不为空
			if (paramStr != null && !paramStr.isEmpty()) {
				// 从连接获取输出流
				os = httpsConnection.getOutputStream();
				// 开始写
				byte[] b = paramStr.getBytes("UTF-8");
				os.write(b, 0, b.length);
			}
			// 如果返回code等于200,接收返回报文
			if (HttpsURLConnection.HTTP_OK
					== httpsConnection.getResponseCode()) {
				// 得到输入流
				is = httpsConnection.getInputStream();
				bis = new BufferedInputStream(is);
				byte[] respByte = new byte[1024];
				while(bis.read(respByte) > 0) {
					// 这个地方注意,字节数组使用new String即可转为字符串
					// toString() 和 Arrays.toString()都不行
					respBuffer.append(new String(respByte, "UTF-8"));
				}
			}
		} catch(Exception e) {
			throw e;
		}
		return respBuffer.toString();
	}
	
	/**
	 * 关闭流和连接
	 */
	private static void closeStreamAndConnect(OutputStream os,
	 InputStream is, BufferedInputStream bis,
	 HttpsURLConnection connection) {
		try {
			connection.disconnect();
		} catch(Exception e) {
		}
		try {
			if (is != null) {
				is.close();
			}
		} catch(Exception e) {
		}
		try {
			if (bis != null) {
				bis.close();
			}
		} catch(Exception e) {
		}
		try {
			if (os != null) {
				os.close();
			}
		} catch(Exception e) {
		}
	}
}
三、发送https请求——校验服务端证书
package com.ykq;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

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

/**
 * 发送https请求
 *
 * @author YKQ
 */
public class SendHttpsUtil {
    /**
     * 设置为校验证书
     * 
     * @param cAalias 证书别名,可用唯一的随机数替代
     * @param certificate 证书路径
     */
    private static void trustAllHttpsCertificates(String cAalias,
     String certificate) throws Exception {
    	 // 证书工厂
	     CertificateFactory certificateFactory =
	      		CertificateFactory.getInstance("X.509");
	     // 秘钥仓库
	     KeyStore keyStore =
	     		 KeyStore.getInstance(KeyStore.getDefaultType());
	     keyStore.load(null);
	     FileInputStream caInputStream
	     		 = new FileInputStream(new File(certificate)); 
	     keyStore.setCertificateEntry(cAalias,
	     	 certificateFactory.generateCertificate(caInputStream));
	     TrustManagerFactory trustManagerFactory =
	      		TrustManagerFactory.getInstance(
	     			TrustManagerFactory.getDefaultAlgorithm());
	     trustManagerFactory.init(keyStore);
	     TrustManager[] trustManagers =
	     		 trustManagerFactory.getTrustManagers();
	     if (trustManagers.length != 1 ||
	     	 !(trustManagers[0] instanceof X509TrustManager)) {
	        throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
	     }
	     X509TrustManager x509TrustManager = (X509TrustManager) trustManagers[0];
	     // 这里传TLS或SSL其实都可以的
	     SSLContext sslContext = SSLContext.getInstance("TLS");
	     // linux中getInstanceStrong获取随机数,可能导致jdk内存溢出,可替换为new SecureRandom()
	     sslContext.init(null,
	     	 new TrustManager[]{x509TrustManager},
	     	  SecureRandom.getInstanceStrong());
	   	 HttpsURLConnection.setDefaultSSLSocketFactory(
	   	 	sslContext.getSocketFactory());
    }
	
	public static String sendHttps(String method, String urlStr, String paramStr,
		Map<String, String> requestProperty, String cAalias, String certificate) {
		OutputStream os = null;
		InputStream is = null;
		BufferedInputStream bis = null;
		HttpsURLConnection httpsConnection = null;
		try {
			// 校验证书
			trustAllHttpsCertificates(cAalias, certificate);
			// 这个地方一定要返回,而不是当成对象传入设置即可
			httpsConnection = getHttpConnect(httpsConnection, urlStr, method, requestProperty);
			// 开始连接
			httpsConnection.connect();
			// 获取返回报文
			String respStr = getRespStr(httpsConnection, paramStr, os, is, bis);
			return respStr;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭输入输出流,关闭链接
			closeStreamAndConnect(os, is, bis, httpsConnection);
		}
		return "";
	}
	
	/**
	 * 获取链接
	 * @throws Exception 
	 */
	private static HttpsURLConnection getHttpConnect(
			HttpsURLConnection httpsConnection, String urlStr,
			String method, Map<String, String> requestProperty)
			 throws Exception {
		try {
			// 获取URL地址
			URL url = new URL(urlStr);
			// 获取URL链接
			httpsConnection = (HttpsURLConnection) url.openConnection();
			// 设置超时时间
			httpsConnection.setConnectTimeout(3000);
			httpsConnection.setReadTimeout(3000);
			// 设置请求方式POST/GET/PUT/DELETE
			httpsConnection.setRequestMethod(method);
			// 不使用缓存
			httpsConnection.setUseCaches(false);
			// 允许输入
			httpsConnection.setDoInput(true);
			// 允许输出
			httpsConnection.setDoOutput(true);
			// 例如设置请求头为json请求,也可以设置其他请求头
			//httpConnection.setRequestProperty("Content-Type",
	           //	  "application/json;charset=utf-8");
			if(requestProperty != null && !requestProperty.isEmpty()) {
				// 遍历map
				Set<Entry<String, String>> propertyEntry
					= requestProperty.entrySet();
				Iterator<Entry<String, String>> iterator
					= propertyEntry.iterator();
				Entry<String, String> entry = null;
				while (iterator.hasNext()) {
					entry = iterator.next();
					httpsConnection.setRequestProperty(entry.getKey(),
							entry.getValue());
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return httpsConnection;
	}
	
	/**
	 * 获取响应体
	 * @throws Exception 
	 */
	private static String getRespStr(HttpsURLConnection httpsConnection,
	 String paramStr, OutputStream os, InputStream is,
	  BufferedInputStream bis) throws Exception {
		StringBuffer respBuffer = new StringBuffer();
		try {
			// 如果参数不为空
			if (paramStr != null && !paramStr.isEmpty()) {
				// 从连接获取输出流
				os = httpsConnection.getOutputStream();
				// 开始写
				byte[] b = paramStr.getBytes("UTF-8");
				os.write(b, 0, b.length);
			}
			// 如果返回code等于200,接收返回报文
			if (HttpsURLConnection.HTTP_OK
					== httpsConnection.getResponseCode()) {
				// 得到输入流
				is = httpsConnection.getInputStream();
				bis = new BufferedInputStream(is);
				byte[] respByte = new byte[1024];
				while(bis.read(respByte) > 0) {
					// 这个地方注意,字节数组使用new String即可转为字符串
					// toString() 和 Arrays.toString()都不行
					respBuffer.append(new String(respByte, "UTF-8"));
				}
			}
		} catch(Exception e) {
			throw e;
		}
		return respBuffer.toString();
	}
	
	/**
	 * 关闭流和连接
	 */
	private static void closeStreamAndConnect(OutputStream os,
	 InputStream is, BufferedInputStream bis,
	  HttpsURLConnection connection) {
		try {
			connection.disconnect();
		} catch(Exception e) {
		}
		try {
			if (is != null) {
				is.close();
			}
		} catch(Exception e) {
		}
		try {
			if (bis != null) {
				bis.close();
			}
		} catch(Exception e) {
		}
		try {
			if (os != null) {
				os.close();
			}
		} catch(Exception e) {
		}
	}
}
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值