首页 > 其他分享 >apache-HttpClient4.5

apache-HttpClient4.5

时间:2024-04-08 16:11:52浏览次数:16  
标签:http requestUrl param HttpClient4.5 org apache import

package com.yonyou.ucf.mdf.sample.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.util.Map;

@Slf4j
public class RequestTool {

    private static final String HEADER_CONTENT_JSON = "application/json";

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static PoolingHttpClientConnectionManager cm = null;

    private static ObjectMapper mapper = new ObjectMapper();

    private static CloseableHttpClient httpClient;

    /**
     * 记录开放平台请求结果
     */
    public static class Response {
        /**
         * 该请求的 http 状态码
         * 200 为正常的返回结果
         */
        private int status;

        /**
         * 请求返回消息
         * 当 status == 200 时会返回 response body 中的字符串
         * 当 status !== 200 时会返回具体的错误信息
         */
        private String result;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }
    }
    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, (TrustStrategy) (x509Certificates, s) -> true);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslsf)
                    .build();

            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(500);
            cm.setDefaultMaxPerRoute(50);

            RequestConfig globalConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(3000)         // 连接池获取连接超时
                    .setConnectTimeout(3000)                   // 连接建立超时
                    .setSocketTimeout(10000)                    // 等待响应超时
                    .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                    .build();
            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(globalConfig).build();
        } catch (Exception ignore) {
        }
    }

    private static CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public static <T> T doGet(String requestUrl, Map<String, Object> paramMap, Class<T> type) throws Exception {
        return mapper.readValue(doGet(requestUrl, paramMap), type);
    }

    public static <T> T doGet(String requestUrl, Map<String, Object> paramMap, TypeReference<T> typeReference) throws Exception {
        return mapper.readValue(doGet(requestUrl, paramMap), typeReference);
    }

    public static <T> T doPost(String requestUrl, Map<String, Object> requestParam, Map<String, Object> requestBody, Class<T> type) throws Exception {
        return mapper.readValue(doPost(requestUrl, null, requestParam, requestBody), type);
    }

    public static <T> T doPost(String requestUrl, Map<String, String> requestHeader, Map<String, Object> requestParam, Map<String, Object> requestBody, Class<T> type) throws Exception {
        return mapper.readValue(doPost(requestUrl, requestHeader, requestParam, requestBody), type);
    }

    public static String doGet(String requestUrl, Map<String, Object> paramMap) {
        try {
            CloseableHttpClient httpClient = getHttpClient();
            StringBuilder param = new StringBuilder(requestUrl.indexOf("?") > 0 ? "&" : "?");
            if (paramMap != null) {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                    param.append("&");
                }
                param.deleteCharAt(param.length() - 1);
            }

            HttpGet get = new HttpGet(requestUrl + param);
            String responseString = httpClient.execute(get, response -> EntityUtils.toString(response.getEntity()));
            get.releaseConnection();
            return responseString;
        } catch (Throwable e) {
            log.error("接口调用异常GET: url: {}, paramMap: {}", requestUrl, paramMap, e);
            JSONObject defaultErrorResp = new JSONObject();
            defaultErrorResp.put("code", 500);
            defaultErrorResp.put("success", false);
            defaultErrorResp.put("message", e.getMessage());
            return defaultErrorResp.toString();
        }
    }

    public static String doPost(String requestUrl, Map<String, String> requestHeader, Map<String, Object> requestParam, Map<String, Object> requestBody) {
        try {
            CloseableHttpClient httpClient = getHttpClient();
            StringBuilder param = new StringBuilder(requestUrl.indexOf("?") > 0 ? "&" : "?");
            if (requestParam != null) {
                for (Map.Entry<String, Object> entry : requestParam.entrySet()) {
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                    param.append("&");
                }
                param.deleteCharAt(param.length() - 1);
            }

            //创建post请求对象
            HttpPost post = new HttpPost(requestUrl + param);
            //设置请求头
            post.setHeader("Content-Type", "application/json; charset=UTF-8");
            if (requestHeader != null) {
                for (Map.Entry<String, String> header : requestHeader.entrySet()) {
                    post.setHeader(header.getKey(), header.getValue());
                }
            }
            //设置请求体
            if (requestBody != null) {
                StringEntity stringEntity = new StringEntity(JSON.toJSONString(requestBody), "UTF-8");
                post.setEntity(stringEntity);
            }
            String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
            post.releaseConnection();
            return responseString;
        } catch (Throwable e) {
            log.error("接口调用异常POST: url: {}, paramMap: {}, requestBody: {}", requestUrl, requestParam, JSON.toJSONString(requestBody), e);
            JSONObject defaultErrorResp = new JSONObject();
            defaultErrorResp.put("code", 500);
            defaultErrorResp.put("success", false);
            defaultErrorResp.put("message", e.getMessage());
            return defaultErrorResp.toString();
        }
    }
}

 

标签:http,requestUrl,param,HttpClient4.5,org,apache,import
From: https://www.cnblogs.com/yangxijun/p/18121518

相关文章

  • Apache漏洞复现
    ApacheHTTPD是一款HTTP服务器,该服务器是现在市场上使用最多的服务器,今天对该中间件做一些漏洞复现ApacheHTTPD换行解析漏洞(CVE-2017-15715)Apache通过mod_php来运行PHP网页影响范围:2.4.0~2.4.29漏洞描述:存在解析漏洞,在解析.php时,会将1.php\x0A当做PHP文件执行,从而绕......
  • vulhub中Apache Solr 远程命令执行漏洞复现(CVE-2019-0193)
    ApacheSolr是一个开源的搜索服务器。Solr使用Java语言开发,主要基于HTTP和ApacheLucene实现。此次漏洞出现在ApacheSolr的DataImportHandler,该模块是一个可选但常用的模块,用于从数据库和其他源中提取数据。它具有一个功能,其中所有的DIH配置都可以通过外部请求的dataC......
  • 海豚调度任务类型Apache SeaTunnel部署指南
    ApacheDolphinScheduler已支持ApacheSeaTunnel任务类型,本文介绍了SeaTunnel任务类型如何创建,任务参数,以及任务样例。一、ApacheSeaTunnelSeaTunnel任务类型,用于创建并执行SeaTunnel类型任务。worker执行该任务的时候,会通过start-seatunnel-spark.sh、start-seatunnel......
  • 使用Apache POI和Jsoup将Word文档转换为HTML
    简介在现代办公环境中,Word文档和HTML页面都是常见的信息表达方式。有时,我们需要将Word文档转换为HTML格式,以便在网页上展示或进行进一步的处理。本文将介绍如何使用ApachePOI库和Jsoup库来实现Word文档到HTML的转换,并处理文档中的图片资源。环境准备Java开发环境Apac......
  • 解析Apache Kafka:在大数据体系中的基本概念和核心组件
    关联阅读博客文章:探讨在大数据体系中API的通信机制与工作原理关联阅读博客文章:深入解析大数据体系中的ETL工作原理及常见组件关联阅读博客文章:深度剖析:计算机集群在大数据体系中的关键角色和技术要点关联阅读博客文章:深入理解HDFS工作原理:大数据存储和容错性机制解析引......
  • Apache Flink 简介
    ApacheFlink简介前言计算引擎大数据计算引擎分为离线计算和实时计算,离线计算就是我们通常说的批计算,代表是HadoopMapReduce、Hive等大数据技术。实时计算也被称作流计算,代表是Storm、SparkStreaming、Flink等大数据技术。计算引擎也在不断更新迭代,下图展示的是每一代计算......
  • 各位学弟学妹们,参与Apache顶级开源项目并没有想象中的难
    在笔者出版《RocketMQ技术内幕》后,并随着分享了60篇+的RocketMQ相关文章,在B站与官方联动组织了RocketMQ源码分析视频后,我被官方授予RocketMQ优秀布道师,也是明证言顺的参与了一个Apaceh顶级开源项目。在这里,和大家一起来分享一下关于如何参与一个开源项目。参与开源项目的......
  • Apache OFBiz 身份验证绕过漏洞 (CVE-2023-51467)
    ApacheOFBizAuthenticationBypassVulnerability(CVE-2023-51467)ApacheOFBizAuthenticationBypassVulnerability(CVE-2023-51467)PublishedbyDikshaOjhaonDecember27,2023SonicWall威胁研究团队在基于Java的Web框架ApacheOFBiz中发现了身份验证绕......
  • Linux - 搭建一套Apache大数据集群
     一、服务器操作系统主机名操作系统node01Centos7.9node02Centos7.9node03Centot7.9 二、大数据服务版本服务版本下载Zookeeper3.5.7DownloadHadoop3.3.6DownloadHive3.xDownloadHbase2.xDownloadSpark3.xDownload......
  • Apache POI源码
    官网:ApachePOI-theJavaAPIforMicrosoftDocumentsReleaseNotes:ChangeLogs:javadocs:ApachePOI5.0.xJavadocsApachePOI4.1.xJavadocsApachePOI4.0.xJavadocsApachePOI3.17JavadocsHSSF-提供读写MicrosoftExcel格式档案的功能。XSSF-提供读写Micr......