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:建议下 ...
随机推荐
- Java面试题中高级进阶(JVM篇01)
前言 本来想着给自己放松一下,刷刷博客,突然被几道面试题难倒!说说堆和栈的区别?什么时候会触发FullGC?什么是Java虚拟机?似乎有点模糊了,那就大概看一下面试题吧.好记性不如烂键盘 *** 12 ...
- Linux系统搭建性能测试监控体系
一.安装Grafana 1.Grafana介绍(默认端口3000): Grafana是一个开源的监控和可视化工具,用于显示和跟踪各种指标,数据和日志,支持多种源,包括influxDB.promethe ...
- NOIP2023模拟2联测23 T2 害怕
NOIP2023模拟2联测23 T2 害怕 好像写了一种出题人意料之外的算法. 思路 在生成树上加入白边,白边和若干条蓝色边形成环,环上的蓝色边必须要分配比该白色边更小的边权(最小生成树). 给每一条 ...
- BeanStalkd 做队列服务
今天无意间看到这个仓库讲php关于 BeanStalkd 的扩展,然后就去了解了一下beanstalkd,才知道它可以用来做队列服务. 话不多说,安装一下试试. 首先 sudo apt search ...
- 社区发布非官方龙架构 .NET 9 SDK 发行版
随着.NET 9的发布,龙芯的Loongarch 架构的.NET 9 SDK的发布也提上了日程,在龙芯.NET 的官方支持之外,今年在社区有一个非官方龙架构 .NET SDK 发行版(https:// ...
- Java 编程的动态性,第 1 部分: 类和类装入
研究类以及 JVM 装入类时所发生的情况 这一有关 Java 编程动态方面的新的系列文章研究了执行 Java 应用程序时幕后所发生的事情.企业 Java专家 Dennis Sosnoski 提供了 J ...
- LinkedHashMap源码分析(基于JDK1.6)
LinkedHashMap类似于HashMap,但是迭代遍历它时,取得"键值对"的顺序是插入次序,或者是最近最少使用(LRU)的次序.只比HashMap慢一点:而在迭代访问时反而更 ...
- MySQL命令行客户端工具之mycli
官网: mycli 目前市面上存在各种五花八门的图形界面客户端,如 phpmyadmin,navicat 以及官方的 MySQL Workbench 等等.而在日常工作或者使用中,通过命令连接 MyS ...
- Blazor 组件库 BootstrapBlazor 中CheckboxList组件介绍
组件介绍 CheckboxList 多选框组控件用于创建多选的复选框组. 他的样子是这样的: 代码也很简单,绑定一个List就行了. <CheckboxList @bind-Value=&quo ...
- HTML5 拖拽接口
1.首先,为了使元素可拖动,要先设置元素为可拖拽 方法:添加draggable属性,设置为 true 注意:链接和图像默认就支持拖拽,另外,如果一个元素中的文本被选中,那么这个元素和他的文本节点此时都 ...