使用httpclient发起https请求时,可能会遇到如下异常:
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:397)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:399)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
代码片段
package com.jalor;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import javax.net.ssl.SSLSocketFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.eclipse.jdt.internal.compiler.ast.Invocation;
import org.springframework.beans.factory.annotation.Autowired;
import net.sf.json.JSONObject;
public class HttpsUtils {
@Autowired
Invocation inv;
/**
* Request Headers
*/
final static String CONTENTTYPE = "application/json;charset=utf-8";
public JSONObject toAskHttps() {
InputStream inputStream = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonstr = null;
try {
//从 inputStream 加载 CA 证书
String path = inv.getRequest().getSession().getServletContext().getRealPath("/xxx/file/CA.cer");
inputStream = new FileInputStream(path);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(inputStream);
//构造含有信任 CA 证书的 KeyStore
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
trustStore.setCertificateEntry("myalias", certificate);
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
// 访问HTTPS
HttpPost httpPost = new HttpPost("");
JSONObject jsonParam = new JSONObject();
jsonParam.put("", "");
StringEntity entity = null;
try {
entity = new StringEntity(jsonParam.toString(), "utf-8");
// 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType(CONTENTTYPE);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 重点
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity());
jsonstr = JSONObject.fromObject(result);
}
catch (Exception e) {
e.printStackTrace();
logger.error(e);
}
return jsonstr;
}
}