peer not authenticated的终极解决方案

使用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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百度没有我的爱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值