首页 > 其他分享 >HTTP服务工具类,包括带参数的 post/http get/http get 方法

HTTP服务工具类,包括带参数的 post/http get/http get 方法

时间:2024-07-16 18:55:24浏览次数:8  
标签:HTTP String get charset httpUrl param httpPost new http

1、导入maven依赖

 <!--apache httpclient 客户端工具包-->
       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

2、工具类 

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HTTP 服务工具类,包括 带参数的 post/http get/htts get 方法
 **/
public class HttpClientUtil {
    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();
    private static HttpClientUtil instance = null;

    private HttpClientUtil() {
    }

    public static HttpClientUtil getInstance() {
        if (instance == null) {
            instance = new HttpClientUtil();
        }
        return instance;
    }

    /**
     * Description:发送 post请求
     *
     * @param httpUrl 地址
     */
    public String sendHttpPost(String httpUrl) {
        HttpPost httpPost = new HttpPost(httpUrl);
        return sendHttpPost(httpPost, null);
    }

    /**
     * Description:发送 post请求
     *
     * @param httpUrl 地址
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params) {
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            StringEntity stringEntity = new StringEntity(params, "UTF-8");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost, null);
    }

    /**
     * Description:发送 post请求
     *
     * @param httpUrl 地址
     * @param params  参数(格式:key1=value1&key2=value2)
     * @param charset 请求参数字符集
     */
    public String sendHttpPost(String httpUrl, String params, String charset) {
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            StringEntity stringEntity = new StringEntity(params, charset);
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost, charset);
    }

    /**
     * Description:发送 post请求
     *
     * @param httpUrl 地址
     * @param maps    参数
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps) {
        HttpPost httpPost = new HttpPost(httpUrl);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost, null);
    }

    /**
     * Description:发送 post请求
     *
     * @param httpUrl   地址
     * @param headParam 请求头设置的参数
     * @param reqParams 请求参数
     */
    public String sendHttpPost(String httpUrl, Map<String, String> headParam, Map<String, String> reqParams) {
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            for (String key : headParam.keySet()) {
                httpPost.setHeader(key, headParam.get(key));
            }

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (String key1 : reqParams.keySet()) {
                nameValuePairs.add(new BasicNameValuePair(key1, reqParams.get(key1)));
            }

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost, null);
    }

    /**
     * Description:发送 post请求
     *
     * @param httpUrl 地址
     * @param maps    参数
     * @param charset post 携带参数的字符集
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps, String charset) {
        HttpPost httpPost = new HttpPost(httpUrl);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost, charset);
    }

    /**
     * 发送 get请求
     *
     * @param httpUrl 请求地址
     */
    public String sendHttpGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpGet(httpGet, null);
    }

    /**
     * 发送 get请求
     *
     * @param httpUrl 请求地址
     * @param charset 返回数据字符集
     */
    public String sendHttpGet(String httpUrl, String charset) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpGet(httpGet, charset);
    }

    /**
     * 发送 Https get请求
     *
     * @param httpUrl 请求连接
     */
    public String sendHttpsGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpsGet(httpGet, null);
    }

    /**
     * 发送 Https get请求
     *
     * @param httpUrl 请求连接
     * @param charset 返回数据字符集
     */
    public String sendHttpsGet(String httpUrl, String charset) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpsGet(httpGet, charset);
    }

    /**
     * 发送Post请求
     *
     * @param httpPost post 对象
     * @param charset  返回数据字符集
     */
    private String sendHttpPost(HttpPost httpPost, String charset) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            String retMessage = EntityUtils.toString(response.getEntity(), StringUtil.isEmpty(charset) ? "UTF-8" : charset);
            EntityUtils.consume(response.getEntity());
            return retMessage;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResource(response, httpClient);
        }
        return null;
    }

    /**
     * 发送Get请求
     *
     * @param httpGet httpget 对象
     * @param charset 字符集
     */
    private String sendHttpGet(HttpGet httpGet, String charset) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String retMessage = EntityUtils.toString(entity, StringUtil.isEmpty(charset) ? "UTF-8" : charset);
            EntityUtils.consume(response.getEntity());
            return retMessage;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResource(response, httpClient);
        }
        return null;
    }

    /**
     * 发送Get请求Https
     *
     * @param httpGet httpget 对象
     * @param charset 字符集
     */
    private String sendHttpsGet(HttpGet httpGet, String charset) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseContent = null;
        try {
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);
            responseContent = EntityUtils.toString(response.getEntity(), StringUtil.isEmpty(charset) ? "UTF-8" : charset);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResource(response, httpClient);
        }
        return responseContent;
    }

    /**
     * Description:关闭资源
     */
    private void closeResource(CloseableHttpResponse response, CloseableHttpClient httpClient) {
        try {
            // 关闭连接,释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

标签:HTTP,String,get,charset,httpUrl,param,httpPost,new,http
From: https://blog.csdn.net/HJ_20210519/article/details/140343621

相关文章

  • python中os.stat().st_size、os.path.getsize()获取文件大小
    一、os.stat().st_sizeos.stat(filePath)返回读取指定文件的相关属性,然后利用stat模块进行处理。importosos.stat('data_feather_ys.feather')#os.stat_result(st_mode=33206,st_ino=3659174697257342,st_dev=2829373452,st_nlink=1,st_uid=0,st_gid=0,st_size=400......
  • 安防视频监控EasyCVR平台浏览器http可以播放,https不能播放,如何解决?
    安防视频监控/视频集中存储/云存储/磁盘阵列EasyCVR平台基于云边端一体化架构,兼容性强、支持多协议接入,包括国标GB/T28181协议、部标JT808、GA/T1400协议、RTMP、RTSP/Onvif协议、海康Ehome、海康SDK、大华SDK、华为SDK、宇视SDK、乐橙SDK、萤石云SDK等。平台能对外分发RTMP、RT......
  • docker centos7 镜像 systemctl 报错 Failed to get D-Bus connection: Operation not
    从docker下载默认的CentOS镜像没有开启systemd,执行systemctl命令会显示“FailedtogetD-Busconnection:Operationnotpermitted”错误,如果docker创建centos7的容器涉及到systemctl服务操作,或者需要实现容器开机后自动启动服务功能。需要调整镜像并且修改镜像启动方式......
  • RabbitMQ 安装并成功启动后,无法访问http://127.0.0.1:15672/#/
    1.问题描述&解决:安装了最新版RabbitMQ,然后先正常启动也无法访问,然后网上搜呀搜,什么重启服务,使用管理员打开cmd,或者是使用管理员运行下图的RabbitMQservice-start,最后又尝试了rabbitmq-pluginsenablerabbitmq_management这个命令,都无法在火狐浏览器打开http://127.0.0.1:1......
  • 配置 Ubuntu上的 HTTP 服务器(Apache)
    前言如果文件放在VM2上,想在VM1上进行访问,就可以在VM2配置HTTP服务器。最后在VM1的网页访问VM2的文件。1.安装ApacheHTTP服务器:sudoaptupdatesudoaptinstallapache22.确保Apache已启动并设置为开机启动:sudosystemctlstartapache2sudosystemctlenablea......
  • [Windows] 油.管视频下载神器 Gihosoft TubeGet Pro v9.3.88
    描述对于经常在互联网上进行操作的学生,白领等!一款好用的软件总是能得心应手,事半功倍。今天给大家带了一款高科技软件管视频下载神器无需额外付费,永久免费!亲测可运行!!内容目前主要的内容以资源破解,对于学习破解资源有比较大的帮助!但是网络上面错综复杂,很多老旧的版......
  • phpmyadmin getshell
    本文仅供学习参考phpMyadmin是一个以PHP为基础的MySQL数据库管理工具,使网站管理员可通过Web接口管理数据库。一、intooutfile写马条件:1.对web目录需要有写权限能够使用单引号2.secure_file_priv不为null(mysqlinto写入文件:使用需看要secure_file_priv的值,value为“null”......
  • nginx生成自签名SSL证书配置HTTPS
    一、安装nginxnginx必须有"--with-http_ssl_module"模块查看nginx安装的模块:root@ecs-7398:/usr/local/nginx#cd/usr/local/nginx/root@ecs-7398:/usr/local/nginx#./sbin/nginx-Vnginxversion:nginx/1.20.2builtbygcc9.4.0(Ubuntu9.4.0-1ubuntu1~20.04.2)......
  • [SUCTF 2018]GetShell 1
    自增绕过,文件上传打开是一个白的页面,开始信息收集,可以在前端代码中看到,index.php?act=upload尝试访问之后发现是文件上传发现是直接给了源码的,代码解释:这段PHP代码用于处理一个通过HTML表单上传的文件,并检查该文件的内容是否包含任何黑名单中的字符。下面是逐行解释:if($co......
  • HTTP请求的发送:构建与传输的详细剖析
    摘要在网络通信的世界里,HTTP(超文本传输协议)是构建Web应用的基石。HTTP请求是客户端与服务器通信的语言。本文将深入探讨HTTP请求的发送过程,从构建请求到通过TCP/IP协议栈传输的每个细节。1.HTTP请求概述介绍HTTP请求的基本概念和作用。解释HTTP请求与响应的通信模式。2......