HttpClient从基础请求到工具类封装使用详解

后端 潘老师 3周前 (04-01) 17 ℃ (0) 扫码查看

HttpClient是进行HTTP请求的常用工具,熟练掌握它的使用方法,能够让我们更高效地与网络资源进行交互。本文将详细介绍HttpClient的各种使用方式,并给出工具类封装示例。

一、引入httpclient依赖

在使用HttpClient之前,首先要确保项目中引入了相应的依赖。若项目中尚未引入,需在pom.xml文件中添加以下代码:

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

添加这个依赖后,项目就具备了使用HttpClient的基础环境,后续便能调用相关的类和方法来发起HTTP请求。

二、发送GET请求

2.1 无参数GET请求

当我们需要发送不携带参数的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 {
        // 创建默认的CloseableHttpClient实例,用于发送请求
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpGet请求对象,指定请求的URL
            HttpGet httpGet = new HttpGet("https://www.example.com/getDataList");
            // 执行请求并获取响应
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
                // 判断响应状态码是否为200(OK)
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 将响应实体转换为字符串并返回
                    return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
                }
                return null;
            }
        }
    }
}

这段代码中,先创建了CloseableHttpClient实例,接着构建HttpGet请求对象,发送请求后根据响应状态码判断请求是否成功,若成功则返回响应内容。

2.2 带参数GET请求

带参数的GET请求有两种常见实现方式:

  • 直接在URL上拼接参数:直接在请求的URL后面拼接参数,示例如下:
HttpGet httpGet = new HttpGet("https://www.example.com/getDataList?pageIndex=1&pageSize=20");

这种方式简单直接,但当参数较多时,URL可能会变得冗长且不易维护。

  • 使用URIBuilder添加参数:通过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对象,指定请求的URL
            URIBuilder uriBuilder = new URIBuilder("https://www.example.com/getDataList");
            // 添加参数
            uriBuilder.addParameter("pageIndex", "1");
            uriBuilder.addParameter("pageSize", "20");
            // 根据构建好的URI创建HttpGet请求对象
            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;
            }
        }
    }
}

使用URIBuilder添加参数的方式更加灵活,参数管理也更方便,推荐在实际开发中使用。

三、发送POST请求

3.1 无参数POST请求

发送不携带参数的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请求对象,指定请求的URL
            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;
            }
        }
    }
}

该代码与无参数GET请求的代码结构类似,只是将HttpGet换成了HttpPost,用于发送POST请求。

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

以form表单方式发送带参数的POST请求,示例代码如下:

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对象,设置参数和字符编码
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
            // 将参数实体设置到HttpPost请求中
            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;
            }
        }
    }
}

这段代码构建了参数列表,并将其转换为UrlEncodedFormEntity后设置到HttpPost请求中,实现了以form表单方式发送带参数的POST请求。

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

以JSON方式发送带参数的POST请求,代码如下:

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");
            // 设置JSON格式的请求体
            String jsonBody = "{\"id\":\"1\",\"name\":\"新名字\"}";
            StringEntity stringEntity = new StringEntity(jsonBody);
            // 设置请求体的内容类型和字符编码
            stringEntity.setContentType("application/json;charset=utf-8");
            // 将请求体设置到HttpPost请求中
            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;
            }
        }
    }
}

此代码将JSON格式的字符串作为请求体,通过StringEntity设置到HttpPost请求中,并指定了请求体的内容类型,实现了以JSON方式发送带参数的POST请求。

四、发送PUT请求

4.1 无参数PUT请求

发送无参数的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请求对象,指定请求的URL
            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;
            }
        }
    }
}

该代码与无参数的GET、POST请求代码类似,只是使用了HttpPut来发送PUT请求。

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

以form表单方式发送带参数的PUT请求,代码如下:

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对象,设置参数和字符编码
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
            // 将参数实体设置到HttpPut请求中
            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;
            }
        }
    }
}

这段代码与带参数(form表单方式)的POST请求类似,只是将HttpPost替换为HttpPut,用于发送PUT请求。

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

以JSON方式发送带参数的PUT请求,代码如下:

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");
            // 设置JSON格式的请求体
            String jsonBody = "{\"id\":\"1\",\"name\":\"新名字\"}";
            StringEntity stringEntity = new StringEntity(jsonBody);
            // 设置请求体的内容类型和字符编码
            stringEntity.setContentType("application/json;charset=utf-8");
            // 将请求体设置到HttpPut请求中
            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;
            }
        }
    }
}

该代码与以JSON方式发送带参数的POST请求类似,只是使用HttpPut来发送PUT请求。

五、发送DELETE请求

5.1 无参数DELETE请求

发送无参数的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请求对象,指定请求的URL
            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;
            }
        }
    }
}

此代码使用HttpDelete发送无参数的DELETE请求,并根据响应状态码处理响应结果。

六、添加请求头

在实际开发中,请求第三方接口时通常需要添加签名、时间戳等请求头。以POST请求为例,添加请求头的代码如下:

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

GET、PUT、DELETE请求添加请求头的方式与POST请求相同,通过setHeader方法设置相应的请求头信息即可。

七、超时时间设置

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

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;

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

在这段代码中,使用RequestConfig.custom()创建配置对象,设置连接超时时间为5000毫秒,数据传输超时时间为10000毫秒,然后通过httpPost.setConfig(requestConfig)将配置应用到HttpPost请求中。GET、PUT、DELETE请求设置超时时间的方法与之相同。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/16724.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】