1、依赖

<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>

2、HttpClient4Util http请求工具类

点击查看代码

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* Created on 2020-09-29.
* <p>
* Author: zhukang
* <p>
* Description: http请求工具类
*/
@Slf4j
public final class HttpClient4Util { /**
* 连接超时时间
*/
public static final int CONNECT_TIMEOUT = 10000; /**
* 读取超时时间
*/
public static final int SO_TIMEOUT = 30000; private HttpClient4Util() {
} /**
* <HttpClient直接连接接口> <功能详细描述>
*
* @param url 接口URL
* @param params NameValuePair参数
* @param encoding 编码
* @return
* @see [类、类#方法、类#成员]
*/
public static String getResponse4PostByMap(String url, Map<String, Object> params, String encoding) {
return post(url, params, encoding);
} /**
* <HttpClient直接连接接口> <功能详细描述>
*
* @param url 接口URL
* @param params NameValuePair参数
* @param encoding 编码
* @return
* @see [类、类#方法、类#成员]
*/
public static String getResponse4PostByString(String url, String params, String encoding) {
return post(url, params, encoding);
} /**
* <HttpClient直接连接接口> <功能详细描述>
*
* @param url
* @param encoding
* @return
* @throws Exception
* @see [类、类#方法、类#成员]
*/
public static String getResponse4GetAsString(String url, String encoding) {
return get(url, encoding);
} /**
* HttpClient直接连接接口,直接返回数据
*
* @param url 接口URL
* @param params NameValuePair参数
* @param encoding 编码
* @return
* @throws Exception
*/
private static String post(String url, Map<String, Object> params, String encoding) {
log.debug("执行Http Post请求,地址: {} ,参数: {}", url, params); String response = null;
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(params.size());
if (!params.isEmpty()) {
Set<Entry<String, Object>> entrySet = params.entrySet();
for (Entry<String, Object> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
} // 请求方式为key=value的方式
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.addHeader("Accept-Language", "zh-cn");
// 及时释放连接,不缓存连接(防止close_wait)
httpPost.addHeader("Connection", "close"); httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();
httpPost.setConfig(requestConfig); HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
response = EntityUtils.toString(httpEntity, encoding).replaceAll("\r\n", "");
EntityUtils.consume(httpEntity);
} httpPost.abort();
} catch (Exception e) {
log.error("执行Http Post请求失败! Exception: {}", e.getMessage());
} finally {
if(null != httpClient){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.debug("Http Post执行后响应内容:{}", response);
return response;
} /**
* HttpClient直接连接接口,直接返回数据,
*
* @param url 接口URL
* @param params xml字符串参数
* @param encoding 编码
* @return
* @throws Exception
*/
private static String post(String url, String params, String encoding) {
log.debug("执行Http Post请求,地址: {}, 参数: {} ", url, params); String response = null;
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();
httpPost.setConfig(requestConfig); StringEntity postEntity = new StringEntity(params, "UTF-8"); //httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Content-Type", "text/xml");
// 及时释放连接,不缓存连接(防止close_wait)
httpPost.addHeader("Connection", "close");
httpPost.setEntity(postEntity); HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
response = EntityUtils.toString(httpEntity, encoding).replaceAll("\r\n", "");
EntityUtils.consume(httpEntity);
} httpPost.abort();
} catch (Exception e) {
log.error("执行Http Post请求失败! Exception: {}", e.getMessage());
} finally {
if(null != httpClient){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.debug("Http Post执行后响应内容:{} ", response);
return response;
} /**
* HttpClient直接连接接口,直接返回数据
*
* @param url 接口URL
* @param encoding 编码
* @return
* @throws Exception
*/
private static String get(String url, String encoding) {
log.debug("执行Http get请求,地址: {} ", url ); String response = null;
HttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build();
httpGet.setConfig(requestConfig); httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpGet.addHeader("Accept-Language", "zh-cn");
// 及时释放连接,不缓存连接(防止close_wait)
httpGet.addHeader("Connection", "close"); HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
response = EntityUtils.toString(httpEntity, encoding).replaceAll("\r\n", "");
EntityUtils.consume(httpEntity);
} httpGet.abort();
} catch (Exception e) {
e.printStackTrace();
log.error("执行Http GET请求失败! Exception: {}", e.getMessage());
}
log.debug("Http GET执行后响应内容:{}", response);
return response;
} }
 

http请求工具类 HttpClient4Util的更多相关文章

  1. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  2. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  3. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  4. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  5. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  6. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  7. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  8. ajax请求工具类

    ajax的get和post请求工具类: /** * 公共方法类 *  * 使用  变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...

  9. 【原创】标准HTTP请求工具类

    以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...

  10. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

随机推荐

  1. 使用wxpython开发跨平台桌面应用,对WebAPI调用接口的封装

    我在前面介绍的系统界面功能,包括菜单工具栏.业务表的数据,开始的时候,都是基于模拟的数据进行测试,数据采用JSON格式处理,通过辅助类的方式模拟实现数据的加载及处理,这在开发初期是一个比较好的测试方式 ...

  2. 《刚刚问世》系列初窥篇-Java+Playwright自动化测试-4-启动浏览器-基于Maven(详细教程)

    1.简介 上一篇文章,宏哥已经在搭建的java项目环境中添加jar包实践了如何启动浏览器,今天就在基于maven项目的环境中给小伙伴们或者童鞋们演示一下如何启动浏览器. 2.eclipse中新建mav ...

  3. Docker for the Virtualization Admin

    Docker is one of the most successful open source projects in recent history, and organizations of al ...

  4. Windows11 常用软件/环境安装记录

    Windows 编程 - The Tools I use 软件安装和管理 将软件装到统一一个地方,路径简短,不含空格和中文. WinGet 官方 Windows 软件包管理器 WinGet 在安装命令 ...

  5. 记录一个Linux代码移植到Windows平台下的Visual Studio 2022的代码编码格式的问题

    一.前言 工作上与公司的前辈对接,他给了我一份在linux下面编写的代码压缩包,按照道理来说使用条件宏编译不同的windows和linux的API即可实现代码的通用.但是我在Visual Studio ...

  6. 查壳工具之Exeinfo PE

    简介 Exeinfo PE是一款免费.专业的程序查壳软件,可以查看exe.dll程序的编译信息,开发语言,是否加壳,壳的种类以及入口地址等信息. Exeinfo PE下载地址:https://gith ...

  7. CAD快速图层孤立、隐藏、锁定下载

    AutoCAD快速图层孤立.隐藏.锁定插件下载 链接 AutoCAD Quick Layer Isolation, Hide, Lock Plugin Download Link MAG.fas&am ...

  8. 13TB的StarRocks大数据库迁移过程

    公司有一套StarRocks的大数据库在大股东的腾讯云环境中,通过腾讯云的对等连接打通,通过dolphinscheduler调度datax离线抽取数据和SQL计算汇总,还有在大股东的特有的Flink集 ...

  9. Nuxt.js 应用中的 close 事件钩子

    title: Nuxt.js 应用中的 close 事件钩子 date: 2024/12/2 updated: 2024/12/2 author: cmdragon excerpt: close 钩子 ...

  10. 在Windows下为CodeBlocks20.3安装、配置wxWidget3.2.6

    0.前言 CodeBlocks是使用C++编写程序的一个很好的开发环境,最大的好处是它是开源的.免费的,而不仅仅是因为它具有跨平台的能力.还有一个很重要的原因是在CodeBlocks中可以使用wxWi ...