java发送Https的POST请求
unable to find valid certification path to requested target
当对https服务发起请求时,如果不提供证书则会出现以上错误,在测试情况下没有证书时如何发起请求获取数据问题;
HttpsURLConnection
public static String getHttpClient(String method,String url0) throws Exception{
final SSLContext sslContext = SSLContext.getInstance("TLS");
// 使用自定义受信
sslContext.init(null,new TrustManager[]{new CustomTrustManager()},new SecureRandom());
final SSLSocketFactory socketFactory = sslContext.getSocketFactory();
URL url = new URL(url0);
final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setSSLSocketFactory(socketFactory);
httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpsURLConnection.setRequestProperty("Cookie", "M_SESSION=137cffa5-4b37-4dd5-947c-00e0b80aaaba");
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setRequestMethod(method);
/* httpsURLConnection.setConnectTimeout(connectTimeoutLimit);
httpsURLConnection.setReadTimeout(readTimeoutLimit);*/
OutputStream outputStream = null;
InputStream inputStream = null;
String response;
try {
outputStream = httpsURLConnection.getOutputStream();
outputStream.write("".getBytes());
outputStream.flush();
inputStream = httpsURLConnection.getInputStream();
byte[] bytes = IoUtil.read(inputStream, 1024);
response = new String(bytes, "UTF-8");
System.out.println(response);
return response;
} catch (IOException var13) {
throw var13;
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (Exception var12) {
var12.printStackTrace();
}
}
return null;
}
自定义受信
public class CustomTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
HttpClient
public class HttpClientHolder {
private static CloseableHttpClient client;
private static CookieStore cookieStore;
public static HttpClient getHttpsClient() {
if (null != client) {
return client;
}
try {
SSLContext sslContext = SSLContexts.custom().build();
sslContext.init(null,new TrustManager[]{new CustomTrustManager()},new SecureRandom());
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
cookieStore = new BasicCookieStore();
client = HttpClients.custom().setDefaultCookieStore(cookieStore).setSSLSocketFactory(factory).build();
}catch (Exception e) {
e.printStackTrace();
}
return client;
}
public static Cookie getCookie() {
if (cookieStore == null) {
return null;
}
return cookieStore.getCookies().get(0);
}
}
public static List<String> getInstitution(String pageNo) {
if (pageNo == null || "".equals(pageNo)) {
pageNo = "0";
}
String url = "url";
final HttpClient httpsClient = HttpClientHolder.getHttpsClient();
List<NameValuePair> params = new LinkedList<NameValuePair>();
List<String> institutionIDs = new LinkedList<String>();
// 设置参数
params.add(new BasicNameValuePair("op", "getListForm"));
params.add(new BasicNameValuePair("pageNo", pageNo));
// 参数t 随机数 可有可无
params.add(new BasicNameValuePair("t","0.8702144893057147"));
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63");
//httpPost.setHeader("Cookie",HttpClientHolder.getCookie().getValue());
httpPost.setHeader("Cookie", "137cffa5-4b37-4dd5-947c-00e0b80aaaba");
HttpResponse response = httpsClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
String respContent = EntityUtils.toString(entity);
//System.out.println(respContent);
final Document document = Jsoup.parse(respContent);
final Elements elements = document.select("tr[id$=TrID]");
for (Element e : elements) {
final String institutionID = e.attr("id").trim().substring(0,6);
//System.out.println(institutionID);
institutionIDs.add(institutionID);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return institutionIDs;
}
RestTemplate
RestTemplate需要继承SimpleClientHttpRequestFactory重写prepareConnection方法
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (!(connection instanceof HttpsURLConnection)) {
// http
super.prepareConnection(connection,httpMethod);
}
try {
if (connection instanceof HttpsURLConnection) {
// https
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
SSLContext ctx = SSLContexts.custom().loadTrustMaterial(trustStore, anyTrustStrategy).build();
((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
super.prepareConnection(httpsConnection, httpMethod);
}
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
}