jdk自带访问https和apache httpclient访问htts的SLL报错处理

1.JDK访问https

try {

URL url = new URL("https://www.mg.com/miugogate/gateway?service=unifiedLogin&mchntLoginUserName=miugobuyadmin&mchntLoginPwd=21218CCA77804D2BA1922C33E0151105&charset=utf-8&signType=MD5&sign=BE1938CA5FBBCD8BD2BEED0135B96420&token=20130304175557255110&caic=000000000000041");

System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return urlHostName.equals(session.getPeerHost());
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);

TrustManager[] tm = { new SSLTrust() };

SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
System.err.println(sb.toString());

} catch (Exception e) {

e.printStackTrace();
}

需要类:

import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class SSLTrust implements X509TrustManager {

/*
* The default X509TrustManager returned by SunX509. We'll delegate
* decisions to it, and fall back to the logic in this class if the default
* X509TrustManager doesn't trust it.
*/
X509TrustManager sunJSSEX509TrustManager;

public SSLTrust() throws Exception {
// create a "default" JSSE X509TrustManager.

KeyStore ks = KeyStore.getInstance("JKS");

// ks.load(new FileInputStream("trustedCerts"),
// "passphrase".toCharArray());

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");

tmf.init(ks);

TrustManager tms[] = tmf.getTrustManagers();

/*
* Iterate over the returned trustmanagers, look for an instance of
* X509TrustManager. If found, use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
sunJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}

/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("init failure");
}

/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
// do any special handling here, or rethrow exception.
}
}

/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

try {
sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the cert
* chain.
*/
// excep.printStackTrace();
}
}

/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return sunJSSEX509TrustManager.getAcceptedIssuers();
}
}

2.httpclient访问https

try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
client = SSLTrustApache.wrapClient(client);

BufferedReader in = null;

// 实例化HTTP方法
HttpPost request = new HttpPost("https://www.miugopay.com/miugogate/gateway?service=unifiedLogin&mchntLoginUserName=miugobuyadmin&mchntLoginPwd=21218CCA77804D2BA1922C33E0151105&charset=utf-8&signType=MD5&sign=BE1938CA5FBBCD8BD2BEED0135B96420&token=20130304175557255110&caic=000000000000041");
// HttpPost request = new
// HttpPost("http://127.0.0.1:8080/miugogate/GateWay");
// String service = "login_httpclient";
// String name = "wasuadmin";
// String pass = "21218CCA77804D2BA1922C33E0151105";
// String tid = "112";
// String data =
// "service="+service+"&name="+name+"&pass="+pass+"&tid="+tid;
// //需要签名的字段(RSA签名)
// String sign = MD5.getEncodeString(data);
// System.err.println(data);
// System.err.println(sign);

// 创建名/值组列表
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
// parameters.add(new BasicNameValuePair("service",service));
// //订购预售权回调标记
// parameters.add(new BasicNameValuePair("name",name));
// parameters.add(new BasicNameValuePair("pass", pass));
// parameters.add(new BasicNameValuePair("tid", tid));
// parameters.add(new BasicNameValuePair("sign", sign));

// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters);
request.setEntity(formEntiry);
// 执行请求
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
StringBuffer sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}

System.err.println(sb.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

 需要类:

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.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

public class SSLTrustApache {

public static org.apache.http.client.HttpClient wrapClient(org.apache.http.client.HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
return new DefaultHttpClient(mgr, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}

原文地址:https://www.cnblogs.com/yangy608/p/2949965.html