首页 > 其他分享 >http请求方式-CloseableHttpClient

http请求方式-CloseableHttpClient

时间:2022-10-13 19:25:19浏览次数:42  
标签:http 请求 java CloseableHttpClient new org apache import

http请求方式-CloseableHttpClient

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.core.mydemo.http.OrderReqVO;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * httpclient 实现https请求,4.4版本之后,工具类如下
 */
public class CloseableHttpClientUtils {

    private static Logger logger = LoggerFactory.getLogger(CloseableHttpClientUtils.class);
    static CloseableHttpClient httpClient;
    static CloseableHttpResponse httpResponse;

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();

    }

    /**
     * 发送https请求
     *
     * @throws Exception
     */
    public static String sendByHttp(Map<String, Object> params, String url) {
        try {
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> listNVP = new ArrayList<NameValuePair>();
            if (params != null) {
                for (String key : params.keySet()) {
                    listNVP.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listNVP, "UTF-8");
            logger.info("创建请求httpPost-URL={},params={}", url, listNVP);
            httpPost.setEntity(entity);
            httpClient = CloseableHttpClientUtils.createSSLClientDefault();
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
                return jsObject;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpResponse.close();
                httpClient.close();
                logger.info("请求流关闭完成");
            } catch (IOException e) {
                logger.info("请求流关闭出错");
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        OrderReqVO data = new OrderReqVO();
        data.setOrderNum("111123333");
        data.setServerType("take");

        Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(data));

        String url = "https://域名/接口名称";

        System.out.println("返回结果=" + CloseableHttpClientUtils.sendByHttp(map, url));;
    }

}

 

标签:http,请求,java,CloseableHttpClient,new,org,apache,import
From: https://www.cnblogs.com/oktokeep/p/16789357.html

相关文章

  • http请求方式-HttpClient
    http请求方式-HttpClientimportcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.example.core.mydemo.http.OrderReqVO;importorg.a......
  • http请求方式-HttpURLConnection
    http请求方式-HttpURLConnectionimportcom.alibaba.fastjson.JSON;importcom.example.core.mydemo.http.OrderReqVO;importorg.springframework.lang.Nullable;im......
  • scrapy 给单个请求设置超时时间
       meta={'download_timeout':30}     ......
  • http 报文
    一、报文格式:一个HTTP请求报文由请求行(requestline)、请求头部(header)、空行和请求数据4个部分组成,具体格式如下;1.请求报文格式起始行<method>      空格   <r......
  • uni-app发送GET和POST请求方式
    基于上一篇文章对AJAX概念的描述,那么目前流行的uni-app到底是怎么发请求的呢,我会把格式写在下面使用uni.request()发起GET请求:使用uni.request()发起POST请求let......
  • python requests库提示警告:InsecureRequestWarning: Unverified HTTPS request is bei
    在利用requests访问链接,有时有有警告InsecureRequestWarning:UnverifiedHTTPSrequestisbeingmade.Addingcertificatever解决办法:Python3访问HT......
  • watch 监视搜索关键词的变化不断发送请求返回建议
    watch:{keywords:{//yarnaddlodash下载lodash包//import{debounce}from"lodash";引入防抖的函数//每隔700ms执行一次handler......
  • 【HTTP】190-http 状态码竟然可以这样记
    标题皮了一下,但是内容应该算是比较用心的,不是直接抄了一下官方文档和一堆抽象的术语,尽量配合实例解释的通俗一些。基本介绍状态码(StatusCode)和原因短语(ReasonPhrase)用于简......
  • 下载https图片工具类
    普通http工具类httpClient访问https图片会报以下错误javax.net.ssl.SSLHandshakeException:java.security.cert.CertificateException:Nosubjectalternativenames......
  • 45. JS Ajax请求(简明教程)
    1.前言Ajax全称“AsynchronousJavaScriptandXML”,译为“异步JavaScript和XML”,程序员们习惯称之为“阿贾克斯”,它并不是一种技术,而是多种技术的综合体,其中包括Ja......