在对接第三方API接口时,发送httpClient的POST请求时报“peer not authenticated”异常,下边是解决这个异常的方法
避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常 不用导入SSL证书
package com.guoyao.wanxu.utils;
import CertificateException;
import X509Certificate;
import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import org.apache.http.client.HttpClient;
import org.scheme.Scheme;
import org.scheme.SchemeRegistry;
import org.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.sccm.ThreadSafeClientConnManager;
/**
* 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常 不用导入SSL证书
*
* @author
*
*/
public class WebClientDevWrapper {
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = Instance("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();
ister(new Scheme("https", 443, ssf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(regist
ry);
return new DefaultHttpClient(mgr, Params());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
以下是发送请求的方法:
public static String doPostFoodZs(String url, JSONObject jsonRequst) {
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
StringEntity entity;
try {
entity = new String(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
HttpResponse response = WebClientDevWrapper.wrapClient(httpClient).execute(method);
//请求发送成功,并得到响应
if (StatusLine().getStatusCode() == 200) {
//读取服务器返回过来的peerjson字符串数据
result = EntityUtils.toString(Entity(),"utf-8");
}else{
System.out.println("-----请求失败,状态码statusCode:"+StatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论