一、Java请求https
1.1 实现X509TrustManager类
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
1.2 实现HostnameVerifier接口
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;// 直接返回true
}
}
1.3 连接HTTPS
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
public class ConnectionHTTPS {
public static void main(String[] args) throws Exception {
connection("https://127.0.0.1:8443/test");
}
public static void connection(String url) throws Exception {
// 创建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 paths = new URL(url);//重点在这里,需要使用带有URLStreamHandler参数的URL构造方法
HttpsURLConnection connection = (HttpsURLConnection) paths.openConnection();
// 重要
connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
connection.setSSLSocketFactory(ssf);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
// 发送请求参数
OutputStream out = connection.getOutputStream();
out.write("{\"username\":\"test\"}".getBytes());
// 获取响应结果
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String result;
StringBuilder path = new StringBuilder();
while ((result = br.readLine()) != null){
path.append(result);
System.out.println(path);
}
}
}