1. 引入httpclient依赖

首先,需要确认项目中是否已引入过httpclient依赖,如果没有引入过,需要在pom.xml中添加以下代码引入httpclient依赖:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>

2. 发送GET请求

2.1 发送GET请求(无参数)

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.nio.charset.StandardCharsets; public class HttpClientUtils {
public static String doGet() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet("https://www.example.com/getDataList"); try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

2.2 发送GET请求(带参数)

第一种方法是直接在url上拼接上参数,如下所示:

HttpGet httpGet = new HttpGet("https://www.example.com/getDataList?pageIndex=1&pageSize=20");

第二种方法是使用URIBuilder添加参数,如下所示:

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets; public class HttpClientUtils {
public static String doGet() throws IOException, URISyntaxException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { URIBuilder uriBuilder = new URIBuilder("https://www.example.com/getDataList");
uriBuilder.addParameter("pageIndex", "1");
uriBuilder.addParameter("pageSize", "20"); HttpGet httpGet = new HttpGet(uriBuilder.build()); try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

3. 发送POST请求

3.1 发送POST请求(无参数)

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.nio.charset.StandardCharsets; public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("https://www.example.com/updateData"); try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

3.2 发送POST请求(带参数、form表单方式)

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List; public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("https://www.example.com/updateData"); List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("id", "1"));
params.add(new BasicNameValuePair("name", "新名字")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
httpPost.setEntity(formEntity); try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

3.3 发送POST请求(带参数、json方式)

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.nio.charset.StandardCharsets; public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("https://www.example.com/updateData"); String jsonBody = "{\"id\":\"1\",\"name\":新名字}";
StringEntity stringEntity = new StringEntity(jsonBody);
stringEntity.setContentType("application/json;charset=utf-8");
httpPost.setEntity(stringEntity); try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

4. 发送PUT请求

4.1 发送PUT请求(无参数)

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.nio.charset.StandardCharsets; public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPut httpPut = new HttpPut("https://www.example.com/updateData"); try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

4.2 发送PUT请求(带参数、form表单方式)

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List; public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPut httpPut = new HttpPut("https://www.example.com/updateData"); List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("id", "1"));
params.add(new BasicNameValuePair("name", "新名字")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
httpPut.setEntity(formEntity); try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

4.3 发送PUT请求(带参数、json方式)

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.nio.charset.StandardCharsets; public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPut httpPut = new HttpPut("https://www.example.com/updateData"); String jsonBody = "{\"id\":\"1\",\"name\":新名字}";
StringEntity stringEntity = new StringEntity(jsonBody);
stringEntity.setContentType("application/json;charset=utf-8");
httpPut.setEntity(stringEntity); try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

5. 发送DELETE请求

5.1 发送DELETE请求(无参数)

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.nio.charset.StandardCharsets; public class HttpClientUtils {
public static String doDelete() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpDelete httpDelete = new HttpDelete("https://www.example.com/updateData"); try (CloseableHttpResponse httpResponse = httpClient.execute(httpDelete)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} return null;
}
}
}
}

6. 添加请求头

一般情况下,请求第三方接口都需要签名、时间戳等请求头,以POST请求为例,添加请求头的代码如下所示:

httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("signature", "3045022100875efcef9eb54626bb0168a6baa7c61265d0001d49243f");
httpPost.setHeader("timestamp", String.valueOf(System.currentTimeMillis()));

GET请求、PUT请求、DELETE请求添加请求头的方法同上。

7. 超时时间设置

如果需要自定义HTTP请求的连接超时时间和数据传输超时时间,代码如下所示(以POST请求为例):

RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(10000)
.build();
httpPost.setConfig(requestConfig);

GET请求、PUT请求、DELETE请求设置超时时间的方法同上。

8.工具类封装

完整的工具类代码如下所示:

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; public class HttpClientUtils {
/**
* 连接建立超时时间(单位:毫秒)
*/
private static final int CONNECT_TIMEOUT = 5000; /**
* 数据传输超时时间(单位:毫秒)
*/
private static final int SOCKET_TIMEOUT = 10000; /**
* 执行GET请求
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doGet(String url, Map<String, String> headers) throws IOException {
HttpGet httpGet = new HttpGet(url); // 设置请求头
setHeaders(httpGet, headers); return executeRequest(httpGet);
} /**
* 执行GET请求
*
* @param url 请求地址
* @param headers 请求头
* @param params 请求参数
* @return 响应内容字符串
*/
public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException, URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(url); // 设置请求参数
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
} HttpGet httpGet = new HttpGet(uriBuilder.build()); // 设置请求头
setHeaders(httpGet, headers); return executeRequest(httpGet);
} /**
* 执行POST请求(表单方式)
*
* @param url 请求地址
* @return 响应内容字符串
*/
public static String doPost(String url) throws IOException {
return doPost(url, null, null);
} /**
* 执行POST请求(表单方式)
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doPost(String url, Map<String, String> headers) throws IOException {
return doPost(url, headers, null);
} /**
* 执行POST请求(表单方式)
*
* @param url 请求地址
* @param headers 请求头
* @param params 请求参数
* @return 响应内容字符串
*/
public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
HttpPost httpPost = new HttpPost(url); // 设置请求头
setHeaders(httpPost, headers); // 构建表单参数
if (params != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8));
} return executeRequest(httpPost);
} /**
* 执行POST请求(JSON格式)
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doPostJson(String url, Map<String, String> headers) throws IOException {
return doPostJson(url, headers, null);
} /**
* 执行POST请求(JSON格式)
*
* @param url 请求地址
* @param headers 请求头
* @param jsonBody JSON请求体字符串
* @return 响应内容字符串
*/
public static String doPostJson(String url, Map<String, String> headers, String jsonBody) throws IOException {
HttpPost httpPost = new HttpPost(url); // 添加JSON请求头
addJsonHeader(httpPost, headers);
// 添加自定义请求头
setHeaders(httpPost, headers); // 设置JSON请求体
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPost.setEntity(entity);
} return executeRequest(httpPost);
} /**
* 执行PUT请求(JSON格式)
*
* @param url 请求地址
* @param headers 请求头
* @param jsonBody JSON请求体字符串
* @return 响应内容字符串
*/
public static String doPut(String url, Map<String, String> headers, String jsonBody) throws IOException {
HttpPut httpPut = new HttpPut(url); // 添加JSON请求头
addJsonHeader(httpPut, headers);
// 添加自定义请求头
setHeaders(httpPut, headers); // 设置JSON请求体
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPut.setEntity(entity);
} return executeRequest(httpPut);
} /**
* 执行DELETE请求
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doDelete(String url, Map<String, String> headers) throws IOException {
HttpDelete httpDelete = new HttpDelete(url); // 设置请求头
setHeaders(httpDelete, headers); return executeRequest(httpDelete);
} /**
* 创建带超时配置的HttpClient
*
* @return HttpClient实例
*/
private static CloseableHttpClient createHttpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build(); return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
} /**
* 添加JSON请求头
*
* @param httpRequest HTTP请求对象
* @param headers 请求头
*/
private static void addJsonHeader(HttpRequestBase httpRequest, Map<String, String> headers) {
if (headers == null || !headers.containsKey("Content-Type")) {
httpRequest.addHeader("Content-Type", "application/json;charset=utf-8");
}
} /**
* 设置请求头
*
* @param httpRequest HTTP请求对象
* @param headers 请求头
*/
private static void setHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
if (headers == null || headers.isEmpty()) {
return;
} for (Map.Entry<String, String> entry : headers.entrySet()) {
httpRequest.setHeader(entry.getKey(), entry.getValue());
}
} /**
* 统一执行请求并处理响应
*
* @param httpRequest HTTP请求对象
* @return 响应内容字符串
*/
private static String executeRequest(HttpRequestBase httpRequest) throws IOException {
try (CloseableHttpClient httpClient = createHttpClient()) {
try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
return handleResponse(response);
}
}
} /**
* 处理响应结果
*
* @param response HTTP响应对象
* @return 响应内容字符串
*/
private static String handleResponse(CloseableHttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("HTTP请求失败,状态码:" + statusCode);
} HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
return null;
}
}

HttpClient使用方法总结及工具类封装的更多相关文章

  1. JavaFx 生成二维码工具类封装

    原文地址: JavaFx 生成二维码工具类封装 - Stars-One的杂货小窝 之前星之音乐下载器有需要生成二维码功能,当时用的是一个开源库来实现的,但是没过多久,发现那个库依赖太多,有个http- ...

  2. Redis操作Set工具类封装,Java Redis Set命令封装

    Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...

  3. Redis操作List工具类封装,Java Redis List命令封装

    Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...

  4. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  5. (转载) 百度地图工具类封装(包括定位,附近、城市、范围poi检索,反地理编码)

    目录视图 摘要视图 订阅 赠书 | 异步2周年,技术图书免费选      程序员8月书讯      项目管理+代码托管+文档协作,开发更流畅 百度地图工具类封装(包括定位,附近.城市.范围poi检索, ...

  6. 小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_40、Redis工具类封装讲解和实战

    笔记 4.Redis工具类封装讲解和实战     简介:高效开发方式 Redis工具类封装讲解和实战         1.常用客户端 https://redisdesktop.com/download ...

  7. flink---实时项目--day02-----1. 解析参数工具类 2. Flink工具类封装 3. 日志采集架构图 4. 测流输出 5. 将kafka中数据写入HDFS 6 KafkaProducer的使用 7 练习

    1. 解析参数工具类(ParameterTool) 该类提供了从不同数据源读取和解析程序参数的简单实用方法,其解析args时,只能支持单只参数. 用来解析main方法传入参数的工具类 public c ...

  8. 关于TornadoFx和Android的全局配置工具类封装实现及思路解析

    原文地址: 关于TornadoFx和Android的全局配置工具类封装实现及思路解析 - Stars-One的杂货小窝 目前个人开发软件存在设置页面,可以让用户自定义些设置,但我发现,存储数据的代码逻 ...

  9. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

  10. Android Sqlite 工具类封装

    鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用. 该封装类主要支持一下功能 支持多用户数据储存 支持 Sqlite数据库升级 支持传入 Sql 语句建表 支持 SQLit ...

随机推荐

  1. 【python】如何优雅的终止while循环

    1. 背景需求 python需要与外界或终端交互时,常常需要使用while循环一直跑. 如果需要终止程序,一般使用Ctrl+c,此时终端会打印一大堆backtrace,并且无法保留当前运行的状态,非常 ...

  2. SM9-密钥交换

    算法过程 代码实现 ///************************************************************************ // File name: ...

  3. SQL Server与ORACLE数据库存储过程编写的几个不同之处

    一直在使用SQL Server数库的存储过程进行业务数据处理,现在ORACLE上进行存储过程应用,感觉没有MSSQL的方便灵活,总结了以下几点区别: 1.入参数据类型不要书写长度.比如:userNam ...

  4. 将VSCode设置为中文(汉化)

    1.VSCode安装好后默认语言为英文,此汉化过程的VSCode版本为1.42.1,如下图所示: 2.下载安装完成后,打开VSCode,使用快捷键Ctrl+Shift+P,然后在出现的输入框中输入co ...

  5. deepseek等AI工具是程序员技能发展的双刃剑

    2025年,全球已有73%的程序员日常使用AI编码工具(Gartner 2025Q1数据).当我们惊叹于GitHub Copilot生成完整功能模块仅需10秒时,也需要警惕一个现象:新一代程序员在ID ...

  6. xcode 12.3 mac m1

  7. 使用nvm管理node.js版本,方便vue2,vue3开发

    在Vue项目开发过程中,我们常常会遇到同时维护Vue2和Vue3项目的情况.由于不同版本的Vue对Node.js 版本的要求有所差异,这就使得Node.js 版本管理成为了一个关键问题.NVM(Nod ...

  8. element-ui实现table表格的嵌套(table表格嵌套)功能实现

      最近在做电商类型的官网,希望实现的布局如下:有表头和表身,所以我首先想到的就是table表格组件. 表格组件中常见的就是:标题和内容一一对应:像效果图中的效果,只用基础的表格布局是不行的,因此我想 ...

  9. 【计算机】常见CPU指令集发展及其关系

    [计算机]常见 CPU 指令集发展及其关系 CPU 与指令集 任何计算机都有一块 CPU,CPU 有其支持的指令集,根据指令集间的兼容性,一种 CPU 可能同时支持多种指令集. 指令集中记录了 CPU ...

  10. SpringMVC - 谈谈你对SpringMVC的理解

    谈谈你对 Spring MVC 的理解? 普通人:Spring MVC 它是一个MVC框架吧,就是,我们可以使用Spring MVC来开发Web应用...呃 它是基于Servlet上的一个扩展,就是它 ...