使用java 发送https 协议请求

时间:2020-12-20 21:10:59

做银联,微信等网络接口业务需要使用加密协议,本来想使用httpClient,但是想着需要了解下底层实现,所以打算动手写了。

https 需要附加ssl ,对这个有点模糊,所以起初是直接用httpsUrlConnection 进行发送请求,报错。

google之,得到需要构造SSL协议:

StringBuffer strBuff = new StringBuffer();
//创建SSLContext对象,初始化信任管理器
TrustManager[] trust = {new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {

}

public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}};
SSLContext sslContext = null;
BufferedReader reader = null;
try {
sslContext = SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null, trust, new SecureRandom());
//获得工厂
SSLSocketFactory ssf = sslContext.getSocketFactory();
//构造HTTPS协议
URL url = new URL(urlPath);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
//设置证书
con.setSSLSocketFactory(ssf);
//设置超时
con.setReadTimeout(3000);
con.setConnectTimeout(3000);

con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
//设置请求方法
con.setRequestMethod(requestMethod);
//打开连接
con.connect();
//获得输入流,设置编码方式
reader = new BufferedReader(new InputStreamReader(con.getInputStream(),Charset.forName("UTF-8")));
String temp = null;
while((temp=reader.readLine())!=null){
strBuff.append(temp);
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
reader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strBuff.toString();