Java实现Https发送get和post请求

原创 2019-11-05 14:11 阅读(464)次

我们工作中经常需要请求第三方或者自己项目中一些接口,有post和get请求,http协议的实现起来很简单,那么https呢?java中如何实现发送https请求并得到响应数据?java中带了javax.net.ssl.HttpsURLConnection类,可以实现https请求。

下面直接分享我的工具类HttpUtil类,HttpUtil有两个方法httpsGet(String url)与httpsPost(String url),分别处理https的get和post请求,数据都返回String类型,如果返回的是html可以用jsoup工具解读Dom,如果是json直接用fastJson或其他转Json工具包就可以读取数据了

直接分享代码吧:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

public class HttpUtil {

	/**
	 * https get请求
	 * @param url
	 * @return
	 */
	public static String httpsGet(String url){
		String str_return = "";
		HttpsURLConnection conn = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
					new java.security.SecureRandom());
			URL console = new URL(url);
			conn = (HttpsURLConnection) console.openConnection();
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
			conn.connect();
			InputStream is = conn.getInputStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					("ISO-8859-1")));
			String ret = "";
			while (ret != null) {
				ret = br.readLine();
				if (ret != null && !ret.trim().equals("")) {
					str_return = str_return
							+ new String(ret.getBytes("ISO-8859-1"), "utf-8");
				}
			}
		} catch (ConnectException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return str_return;
	}
	/**
	 * https Post请求
	 * @param url
	 * @return
	 */
	public static String httpsPost(String url,Map parameters){
		String str_return = "";
		HttpsURLConnection conn = null;
		try {
			StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();){
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(),"utf-8"));
                params.append("&");
            }

            if (params.length() > 0) {
                params = params.deleteCharAt(params.length() - 1);
            }
			
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
					new java.security.SecureRandom());
			URL console = new URL(url);
			conn = (HttpsURLConnection) console.openConnection();
			conn.setRequestMethod("POST");
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
			conn.setDoOutput(true);
			byte[] b = params.toString().getBytes();
			conn.getOutputStream().write(b, 0, b.length);
			conn.getOutputStream().flush();
			conn.getOutputStream().close();
			
			conn.connect();
			InputStream is = conn.getInputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					("ISO-8859-1")));
			String ret = "";
			while (ret != null) {
				ret = br.readLine();
				if (ret != null && !ret.trim().equals("")) {
					str_return = str_return
							+ new String(ret.getBytes("ISO-8859-1"), "utf-8");
				}
			}
		} catch (ConnectException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return str_return;
	}
	//测试一下
	public static void main(String[] args) throws Exception {
		String string = HttpUtil2.httpsGet("https://www.baidu.com");
		System.out.println(string);
	}
}
其中还需要其他两个类

TrustAnyHostnameVerifier.java

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class TrustAnyHostnameVerifier implements HostnameVerifier {

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

}
TrustAnyTrustManager.java

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class TrustAnyTrustManager implements X509TrustManager {

	public void checkClientTrusted(X509Certificate[] arg0, String arg1)
			throws CertificateException {
		// TODO Auto-generated method stub

	}

	public void checkServerTrusted(X509Certificate[] arg0, String arg1)
			throws CertificateException {
		// TODO Auto-generated method stub

	}

	public X509Certificate[] getAcceptedIssuers() {
		return new X509Certificate[] {};
	}

}

这三个类直接到工程里就可以用了