java 远程调用 httpclient 调用https接口 忽略SSL认证

这篇具有很好参考价值的文章主要介绍了java 远程调用 httpclient 调用https接口 忽略SSL认证。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

httpclient 调用https接口,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。下面是忽略校验过程的代码类:SSLClient 

package com.pms.common.https;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 用于进行Https请求的HttpClient
 * @ClassName: SSLClient
 * @Description: TODO
 *
 */
public class SSLClient extends DefaultHttpClient {

    public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, getTrustingManager(), null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }

    private static TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        return trustAllCerts;
    }
}

然后再调用的远程get、post请求中使用SSLClient 创建Httpclient ,代码如下:文章来源地址https://www.toymoban.com/news/detail-679675.html

package com.pms.common.https;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpsClientUtil {

    /**
     * post请求(用于请求json格式的参数)
     * @param url
     * @param param
     * @return
     */
    @SuppressWarnings("resource")
    public static String doHttpsPost(String url, String param, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            StringEntity se = new StringEntity(param);
            se.setContentType("application/json;charset=UTF-8");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * post请求(用于key-value格式的参数)
     * @param url
     * @param params
     * @return
     */
    @SuppressWarnings("resource")
    public static String doHttpsPostKV(String url, Map<String,Object> params, String charset, Map<String, String> headers){
        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient httpClient = new SSLClient();
            // 实例化HTTP方法
            HttpPost httpPost = new HttpPost();

            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }

            httpPost.setURI(new URI(url));

            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));

                //System.out.println(name +"-"+value);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            HttpResponse response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if(code == 200){    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(),"utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }

                in.close();

                return sb.toString();
            }
            else{   //
                System.out.println("状态码:" + code);
                return null;
            }
        }
        catch(Exception e){
            e.printStackTrace();

            return null;
        }
    }

    @SuppressWarnings("resource")
    public static String doHttpsGet(String url, Map<String, Object> params, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try{
            if(params !=null && !params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<>(params.size());
                for (String key :params.keySet()){
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                url +="?"+EntityUtils.toString(new UrlEncodedFormEntity(pairs), charset);
            }
            httpClient = new SSLClient();
            httpGet = new HttpGet(url);
//            httpGet.addHeader("Content-Type", "application/json");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpGet.addHeader(next.getKey(), next.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }


    
    //get 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8
    //带参数
    @SuppressWarnings("resource")
    public static String doHttpsFormUrlencodedGetRequest(String url, Map<String, Object> params, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try{
            if(params !=null && !params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<>(params.size());
                for (String key :params.keySet()){
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                url +="?"+EntityUtils.toString(new UrlEncodedFormEntity(pairs), charset);
            }
            httpClient = new SSLClient();
            httpGet = new HttpGet(url);
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//            httpGet.addHeader("Content-Type", "application/json");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpGet.addHeader(next.getKey(), next.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    //post 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8
    //带参数
    @SuppressWarnings("resource")
    public static String doHttpsFormUrlencodedPostRequest(String url, String param, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            StringEntity se = new StringEntity(param);
            se.setContentType("application/x-www-form-urlencoded;charset=utf-8");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    //post 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8
    //不带参数  或者参数拼接在url中
    public static String doHttpsFormUrlencodedPostNoParam(String url, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
//            url = url+URLEncoder.encode("{1}", "UTF-8");
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    //传文件到远程post接口
    public static String sendPostWithFile(String url, String param,Map<String, String> headers,File file) throws Exception{
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", new FileBody(file));
            HttpEntity multipartEntity = builder.build();
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            httpPost.setEntity(multipartEntity);
            StringEntity se = new StringEntity(param);
//            se.setContentType("multipart/form-data;charset=utf-8");
//            se.setContentEncoding(new BasicHeader("Content-Type", "multipart/form-data;charset=utf-8"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);

            //获取接口返回值
            InputStream is = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            StringBuffer bf = new StringBuffer();
            String line= "";
            while ((line = in.readLine()) != null) {
                bf.append(line);
            }

            System.out.println("发送消息收到的返回:"+bf.toString());
            return bf.toString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
       return result;

    }

    /**
     * @param @param  url
     * @param @param  formParam
     * @param @param  proxy
     * @param @return
     * @return String
     * @throws
     * @Title: httpPost
     * @Description: http post请求
     * UrlEncodedFormEntity Content-Type=application/x-www-form-urlencoded
     */
    public static String httpPostbyFormHasProxy(String url, Map<String,String> param,Map<String, String> headers,File file) throws IOException {

        log.info("请求URL:{}", url);
        long ls = System.currentTimeMillis();
        HttpPost httpPost = null;
        HttpClient httpClient = null;
        String result = "";
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", new FileBody(file));
            HttpEntity multipartEntity = builder.build();
            httpPost = new HttpPost(url);
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            List<NameValuePair> paramList = transformMap(param);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, "utf8");
            httpPost.setEntity(formEntity);
            httpClient = new SSLClient();
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int code = httpResponse.getStatusLine().getStatusCode();
            log.info("服务器返回的状态码为:{}", code);

            if (code == HttpStatus.SC_OK) {// 如果请求成功
                    result = EntityUtils.toString(httpResponse.getEntity());

            }

        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally {
            if (null != httpPost) {
                httpPost.releaseConnection();
            }
            long le = System.currentTimeMillis();
            log.info("返回数据为:{}", result);
            log.info("http请求耗时:ms", (le - ls));
        }
        return result;

    }

    /**
     * @param @param  params
     * @param @return
     * @return List<NameValuePair>
     * @throws @Title: transformMap
     * @Description: 转换post请求参数
     */
    private static List<NameValuePair> transformMap(Map<String, String> params) {
        if (params == null || params.size() < 0) {// 如果参数为空则返回null;
            return new ArrayList<NameValuePair>();
        }
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> map : params.entrySet()) {
            paramList.add(new BasicNameValuePair(map.getKey(), map.getValue()));
        }
        return paramList;
    }

}

到了这里,关于java 远程调用 httpclient 调用https接口 忽略SSL认证的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • HttpClient未能为 SSL/TLS 安全通道建立信任关系,忽略SSL验证

    参考 https://www.cnblogs.com/RaymonGoGo/p/16705733.html

    2024年02月02日
    浏览(24)
  • 解决远程调用三方接口:javax.net.ssl.SSLHandshakeException报错

    最近在对接腾讯会议API接口,在鉴权完成后开始调用对方的接口,在此过程中出现调用报错:javax.net.ssl.SSLHandshakeException。 当你在进行https请求时,JDK中不存在三方服务的信任证书,导致出现错误javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败。

    2024年02月13日
    浏览(40)
  • HTTPS请求忽略SSL证书

    现场环境: 后端服务部署在docker内,远程调用https接口,线上报错: unable to find valid certification path to requested target 解决方案: 设置SSLSocketFactory忽略证书校验 实现案例: 使用的cn.hutool.http.HttpRequest工具类请求的数据,支持设置头部、表单、body、超时时间等关键信息 工具类 SSL

    2024年02月11日
    浏览(43)
  • RestTemplate HTTPS请求忽略SSL证书

    使用RestTemplate发送HTTPS请求的时候,出现了这样的一个问题: RestTemplate 默认不支持https协议 解决方案:         第一种是忽略认证         第二种是导入证书,比较复杂(比第一种安全)  这里说一下第一种解决方案,忽略认证 版本:Spring Boot2.x RestTemplateConfig 测试代

    2024年02月10日
    浏览(41)
  • 基于 httpClient 请求 Https接口

    代码如下,亲测可用

    2024年01月20日
    浏览(35)
  • curl 忽略https的ssl的证书验证

    今天使用curl 测试url请求出现了需要ssl证书的验证 curl的用法

    2024年02月17日
    浏览(34)
  • 请求第三方Https地址忽略SSL证书校验

    说明:个人使用记录 需要在请求之前忽略ssl协议,这里是直接使用静态方法初始化时就执行了 也需要在请求接口之前忽略SSL

    2024年04月10日
    浏览(36)
  • Java调用https接口添加证书

    将代码复制到工程中  执行完毕没有报错会在工程下面生成jssecacerts文件 将文件放到jdk/jre/lib/security/路径下,具体试实际路径为准,我存放的位置是: /usr/local/apps/jdk1.7.0_79/jre/lib/security/jssecacerts 在调用https接口的实现类中加入以下代码,指定证书位置: 注意:hostname.equals(\\\"

    2024年02月12日
    浏览(36)
  • [最新]简易版本Java HttpClient POST请求调用OpenAI(ChatGPT3/3.5/4)相关接口核心方法(附100个OpenAI/ChatGPT key)

    前言 当下,OpenAI 存在着许多令人惊叹的技术,如 ChatGPT3/3.5/4,它们能够生成高质量的文章、翻译语言、自动生成代码,并且在许多领域都取得了广泛的应用。本文将向您介绍如何使用 Java HttpClient 调用 OpenAI 的 ChatGPT3/3.5/4 接口(如果需要支持Spring,并提供了 100 个 OpenAI/Chat

    2023年04月27日
    浏览(49)
  • Feign忽略Https的SSL最佳方案(且保证负载均衡将失效)

    同时解决Https的SSL证书验证问题和feign不支持Patch请求方法的问题 代码 1. 工具类 OkHttpUtils.java 代码 2. 工具类 FeignConfiguration.java

    2024年02月13日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包