http请求工具类 HttpClient4Util
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的更多相关文章
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- C#实现的UDP收发请求工具类实例
本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...
- ajax请求工具类
ajax的get和post请求工具类: /** * 公共方法类 * * 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...
- 【原创】标准HTTP请求工具类
以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
随机推荐
- Redis常见面试题:ZSet底层数据结构,SDS、压缩列表ZipList、跳表SkipList
文章目录 一.Redis数据结构概述 1.1 Redis有哪些数据类型 1.2 Redis本质是哈希表 1.3 Redis的哈希冲突与渐进式rehash 1.4 数据结构底层 1.4.1 简单动态字符 ...
- 开源 - Ideal库 -获取特殊时间扩展方法(四)
书接上回,我们继续来分享一些关于特殊时间获取的常用扩展方法. 01.获取当前日期所在月的第一个指定星期几 该方法和前面介绍的获取当前日期所在周的第一天(周一)核心思想是一样的,只是把求周一改成求周几而 ...
- P4253 SCOI2015 小凸玩密室
P4253 SCOI2015 小凸玩密室 一道紫色的 dp. 思路 首先读题: 要保证任意时刻所有被点亮的灯泡必须连通 在点亮一个灯泡后必须先点亮其子树所有灯泡才能点亮其他灯泡 考虑设 \(g[u][ ...
- (Python基础教程之六)Python中的关键字
Python基础教程 在SublimeEditor中配置Python环境 Python代码中添加注释 Python中的变量的使用 Python中的数据类型 Python中的关键字 Python字符串操 ...
- pikachu平台XXE漏洞通关教程详解
声明! 如涉及侵权马上删除文章,笔记只是方便各位师傅的学习和探讨,文章所提到的网站以及内容,只做学习交流,其他均与本人无关,切勿触碰法律底线,否则后果自负!!!! 文章来自个人csdn博客,地址:ht ...
- LiV-GS: LiDAR-Vision Integration for 3D Gaussian Splatting SLAM in Outdoor Environments
arxiv |哈工大发布 LiV-GS:户外环境中基于3D高斯泼溅的LiDAR-视觉集成SLAM系统 [LiV-GS: LiDAR-Vision Integration for 3D Gaussian ...
- 一图一知之python3数据类型
记录python数据类型和相关的一些知识点
- Qt 子窗口 隐藏标题栏的图标,在任务栏上的不显示
Qt子窗口使用Qt::Dialog样式时,隐藏窗口标题栏图标方法: this->setWindowIcon(QIcon()); Qt子窗口,在任务栏上的不显示,最简单的方法是设置Qt::Tool ...
- 【Amadeus原创】华为一键强制关闭后台应用的终极解决方法
华为手机速度是快,用起来很顺手,但是最让人头疼的,就是紧急情况开会,我音乐关不了. 上划把全部应用删掉,也没用. 经过一阵子摸索,发现终极办法: 1, 打开华为自带的 手机助手- 应用启动管理 2, ...
- 虚拟机搭建FISCO BCOS的区块链浏览器
一键搭建 注:根据官方文档搭建,大部分与官方文档相似.我自己修改了部分代码,并对部分报错进行了解决这次使用的是一键搭建,适合前后端同机部署,快速体验的情况使用 具体安装步骤 依赖环境 环境 版本 Ja ...