import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
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.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTPS工具类.
*
*/
public class HttpsUtils {
private static Logger logger = LoggerFactory.getLogger(HttpsUtils.class);
private static final class DefaultTrustManager 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;
}
}
/**
* 发送GET请求.
*
* @param url
* @param param
* @return
*/
public static String sendGet(String url, String param, String token) {
// 参数内容为空,直接返回
if(StringUtils.isEmpty(param) || "{}".equals(param)){
return null;
}
String result = "";// 结果内容
try{
// 获取连接
HttpsURLConnection httpsConn = getHttpsURLConnection(url, "GET", token);
// 设置文件长度
httpsConn.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length));
// 获取返回结果
result = getResultFromStream(httpsConn.getInputStream());
}catch(Exception e){
logger.error(url + param + "发送GET请求出现异常!", e);
}
return result;
}
/**
* 发送POST请求.
*
* @param url
* @param param
* @param token
* @return
*/
public static String sendPost(String url, String param, String token) {
// 参数内容为空,直接返回
if(StringUtils.isEmpty(param) || "{}".equals(param)){
return null;
}
String result = "";// 结果内容
try{
// 获取连接
HttpsURLConnection httpsConn = getHttpsURLConnection(url, "POST", token);
// 设置文件长度
httpsConn.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length));
// 添加参数信息
setParamToStream(httpsConn.getOutputStream(), param);
// 获取返回结果
result = getResultFromStream(httpsConn.getInputStream());
}catch(Exception e){
logger.error(url + param + "发送POST请求出现异常!", e);
}
return result;
}
/**
* 获取请求连接.
*
* @param url
* @param method
* @param token
* @return
* @throws IOException
*/
private static HttpsURLConnection getHttpsURLConnection(String url, String method, String token) throws IOException {
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
SSLSocketFactory ssf = ctx.getSocketFactory();
URL httpsUrl = new URL(url);
HttpsURLConnection httpsConn = (HttpsURLConnection) httpsUrl.openConnection();
httpsConn.setSSLSocketFactory(ssf);
httpsConn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
httpsConn.setRequestMethod(method);
// post请求参数
if("POST".equals(method.toUpperCase())){
httpsConn.setDoInput(true);
httpsConn.setDoOutput(true);
}
httpsConn.setRequestProperty("accept", "application/json");
httpsConn.setRequestProperty("connection", "Keep-Alive");
httpsConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 震坤行数据传输时,token内容需要放到header中验证
if(StringUtils.isNotEmpty(token)){
httpsConn.setRequestProperty("token", token);
}
return httpsConn;
}
/**
* 从输入流中获取结果信息.
*
* @param is
* @return
* @throws IOException
*/
private static String getResultFromStream(InputStream is){
String result = "";
BufferedReader in = null;
try{
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("从输入流中获取结果信息出现异常!", e);
}
// 使用finally块来关闭输出流
finally{
try{
if(in != null){
in.close();
}
}
catch(Exception ex){
logger.error("关闭输入流出现异常!", ex);
}
}
return result;
}
/**
* 向输出流中添加参数内容.
*
* @param os
* @param param
* @throws IOException
*/
private static void setParamToStream(OutputStream os, String param){
OutputStreamWriter out = null;
try {
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(os, "UTF-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
} catch (Exception e) {
logger.error(param + "向输出流中添加参数内容出现异常!", e);
}
// 使用finally块来关闭输出流
finally{
try{
if(out != null){
out.close();
}
}
catch(Exception ex){
logger.error(param + "关闭输出流出现异常!", ex);
}
}
}
}
httpsUtils外部接口调用
最新推荐文章于 2022-07-29 09:33:05 发布