httpClient傳送https請求程式碼
阿新 • • 發佈:2018-11-17
package com.lvmama.dest.dianping; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; public class TestHuiping { static String url = "https://***/HC_API/api.php"; public static void main(String[] args) { test(); } public static void test(){ HttpPost httpPost = null; try { String param = "{\"HotelID\":\"637ac99596e0d635\"***\"Method\":\"getHotel\"}"; httpPost = new HttpPost(url); HttpEntity requestEntity = new StringEntity(param); httpPost.setEntity(requestEntity); HttpClient httpClient = createHttpsClient(10000,10000); HttpResponse resp = httpClient.execute(httpPost); HttpEntity entity = resp.getEntity(); String responseStr = EntityUtils.toString(entity, "UTF-8"); if (entity.getContentType() == null) { responseStr = new String(responseStr.getBytes("iso-8859-1"), "UTF-8"); } EntityUtils.consume(entity); System.out.println(responseStr); // String str = HttpsUtil.requestPostHttpsData(url, param); // System.out.println(str); } catch (Exception e) { e.printStackTrace(); } } public static HttpClient createHttpsClient(int connectionTimeout,int soTimeout) { try { HttpClient httpClient = new DefaultHttpClient(); //建立預設的httpClient例項 HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, soTimeout); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null); SSLSocketFactory socketFactory = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); return httpClient; } catch (Exception e) { e.printStackTrace(); } return null; } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } }
</pre><pre code_snippet_id="1818761" snippet_file_name="blog_20160809_3_8076164" name="code" class="java">
javax.net.ssl.SSLException: hostname in certificate didn't match
這個錯誤通過SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER避免