出现此情况基本原因就是SSL证书的问题,有的时候访问成功有的时候访问失败
失败的代码:
/**
* post请求
*
* @param url
* @param json
* @return
*/
public static JSONObject doPost(String url, String json) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = new JSONObject();
try {
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
//判断返回值是否是json格式,如果不是,进行处理
if (!StringDeal.isStringJson(result)) {
response.put("error", result);
return response;
}
response = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new ServiceException(e.toString());
}
return response;
}
修复后的代码:
/**
* post请求
*
* @param url
* @param json
* @return
*/
public static JSONObject doPost(String url, String json) {
// 可能会出现 javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
// DefaultHttpClient client = new DefaultHttpClient();
org.apache.http.client.HttpClient client = wrapClient(url);
HttpPost post = new HttpPost(url);
JSONObject response = new JSONObject();
try {
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
//判断返回值是否是json格式,如果不是,进行处理
if (!StringDeal.isStringJson(result)) {
response.put("error", result);
return response;
}
response = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new ServiceException(e.toString());
}
return response;
}
private static org.apache.http.client.HttpClient wrapClient(String host) {
org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(org.apache.http.client.HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}