package com.tusvn.util;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class HttpsUtils {
/**
* 只信任特定机构颁发的证书
* 安全,域名校验,建议使用
* @return
*/
public static CloseableHttpClient createSSLClient() {
Security.addProvider(new BouncyCastleProvider());
try {
// load CA certificate
//PEMReader reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get("src/main/resources/ca.crt")))));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInputStream = new ByteArrayInputStream(Files.readAllBytes(Paths.get("src/main/resources/ca.crt")));
X509Certificate caCert = null;
while (caInputStream.available() > 0) {
caCert = (X509Certificate) cf.generateCertificate(caInputStream);
}
caInputStream.close();
//X509Certificate caCert = (X509Certificate) reader.readObject();
//reader.close();
// CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null,null);
caKs.setCertificateEntry("ca-certificate", caCert);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(caKs,null).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}catch (Exception e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
* 信任所有的证书
* 有风险,域名、ip方式皆可,不建议使用
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
// 使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
// NoopHostnameVerifier类: 作为主机名验证工具,实质上关闭了主机名验证,它接受任何
// 有效的SSL会话并匹配到目标主机。
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
* 模拟发送 post 请求
*/
public static String doGet(String url) {
// 构建POST请求 请求地址请更换为自己的。
HttpGet get = new HttpGet(url);
InputStream inputStream = null;
String result = "";
try {
// 使用之前写的方法创建httpClient实例
CloseableHttpClient httpClient = createSSLClient();
HttpResponse response = httpClient.execute(get);
result=getResponseMessage(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 模拟发送 post 请求
*/
public static String doPost(String url, String data) {
// 构建POST请求 请求地址请更换为自己的。
HttpPost post = new HttpPost(url);
InputStream inputStream = null;
String result = "";
try {
// 使用之前写的方法创建httpClient实例
// CloseableHttpClient httpClient = createSSLClient();
CloseableHttpClient httpClient = createSSLClientDefault();
// 构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Close");
// 构建消息实体
StringEntity entity = new StringEntity(data, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
post.setEntity(entity);
// 发送请求
HttpResponse response = httpClient.execute(post);
result=getResponseMessage(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 模拟发送 post 请求
*/
public static String doPost(String url, Map<String,Object> params) {
// 构建POST请求 请求地址请更换为自己的。
HttpPost post = new HttpPost(url);
InputStream inputStream = null;
String result = "";
try {
// 使用之前写的方法创建httpClient实例
// CloseableHttpClient httpClient = createSSLClient();
CloseableHttpClient httpClient = createSSLClientDefault();
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
try {
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 发送请求
HttpResponse response = httpClient.execute(post);
result=getResponseMessage(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
private static String getResponseMessage(HttpResponse response) throws ParseException, IOException {
HttpEntity entity = response.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return resp;
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("grant_type", "client_credentials");
map.put("scope", "public");
map.put("client_id", "test");
map.put("client_secret", "123456");
String res = HttpsUtils.doPost("https://127.0.0.1:8080/oauth/token", map);
System.out.println(res);
}
}
依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.64</version>
</dependency>