java 使用post或者get请求出现 javax.net.ssl.SSLHandshakeException

问题描述:使用Java HttpClient 请求https接口时本地环境没有,但是部署到Linux服务器上出现报错

报错内容

open-jdk版本是1.8.0_301
在调用https接口时,出现以下错误

javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
	at sun.security.ssl.Handshaker.activate(Handshaker.java:529)
	at sun.security.ssl.SSLSocketImpl.kickstartHandshake(SSLSocketImpl.java:1492)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1361)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)

解决办法

以下提供两种解决办法

1、修改jdk配置文件

解决办法:找到jdk 1.8安装目录,

找到 安装目录 里面的lib\security 下面有个java.security。

**找到对应的SSLv3,TLSv1, TLSv1.1, 注释掉,重启项目就好了**

linux查找jdk安装目录:

which java

ls -lrt /usr/bin/java

ls -lrt /etc/alternatives/java

java 使用post或者get请求出现 javax.net.ssl.SSLHandshakeException_第1张图片

2、修改HttpClient 发包器

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * @author: dwl
 * @create: 2021-06-07 10:33
 **/

public class HTTPClientImpl {
    final String HTTPS = "https";
    final String HTTP = "http";
    CloseableHttpClient httpClient;
    HTTPClientData httpClientData = new HTTPClientData();

    /**
     * 无参构造方法,创建并初始化httpClient
     */
    public HTTPClientImpl(){
        TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            e.printStackTrace();
        }
        assert sslContext != null;
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE);

        Registry<ConnectionSocketFactory> socketFactoryRegistry =
                RegistryBuilder.<ConnectionSocketFactory> create()
                        .register(HTTPS, sslsf)
                        .register(HTTP, new PlainConnectionSocketFactory())
                        .build();

        BasicHttpClientConnectionManager connectionManager =
                new BasicHttpClientConnectionManager(socketFactoryRegistry);

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).setConnectionManager(connectionManager).build();
    }

    /**
     * GET请求目标URI
     * @param uri 目标URI
     */
    public HTTPClientData doGet(URI uri){
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);

        sendRequest(httpGet);
        return httpClientData;
    }

    public HTTPClientData doPostJSON(URI uri, String jsonString){
        // 创建Post请求
        HttpPost httpPost = new HttpPost(uri);

        StringEntity entity = new StringEntity(jsonString, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        sendRequest(httpPost);
        return httpClientData;
    }

    public HTTPClientData doDelete(URI uri){
        // 创建Delete请求
        HttpDelete httpDelete = new HttpDelete(uri);

        sendRequest(httpDelete);
        return httpClientData;
    }

    public void sendRequest(HttpRequestBase httpRequest){
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpRequest);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            httpClientData.setAllHeaders(response.getAllHeaders());
            httpClientData.setStatus(response.getStatusLine());
//            System.out.println("响应包头为:" + Arrays.toString(response.getAllHeaders()));
//            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                httpClientData.setContent(EntityUtils.toString(responseEntity));
                httpClientData.setContentLength(responseEntity.getContentLength());
                httpClientData.setContentEncoding(responseEntity.getContentEncoding());
                httpClientData.setContentType(responseEntity.getContentType());
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
//                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
import org.apache.http.Header;
import org.apache.http.StatusLine;

import java.util.Arrays;

/**
 * @author: dwl
 * @create: 2021-06-16 13:17
 **/

public class HTTPClientData {
    Header[] AllHeaders;
    StatusLine Status;
    long ContentLength;
    Header ContentEncoding;
    Header ContentType;
    String Content;

    public Header[] getAllHeaders() {
        return AllHeaders;
    }

    @Override
    public String toString() {
        return "HTTPClientData{" +
                "AllHeaders=" + Arrays.toString(AllHeaders) +
                ", Content='" + Content + '\'' +
                '}';
    }

    public void setAllHeaders(Header[] allHeaders) {
        AllHeaders = allHeaders;
    }

    public StatusLine getStatus() {
        return Status;
    }

    public void setStatus(StatusLine status) {
        Status = status;
    }

    public long getContentLength() {
        return ContentLength;
    }

    public void setContentLength(long contentLength) {
        ContentLength = contentLength;
    }

    public Header getContentEncoding() {
        return ContentEncoding;
    }

    public void setContentEncoding(Header contentEncoding) {
        ContentEncoding = contentEncoding;
    }

    public Header getContentType() {
        return ContentType;
    }

    public void setContentType(Header contentType) {
        ContentType = contentType;
    }

    public String getContent() {
        return Content;
    }

    public void setContent(String content) {
        Content = content;
    }
}

你可能感兴趣的:(java,ssl)