Java通过HttpClient进行HTTP请求的代码详解
作者:MerkleJqueryRu 发布时间:2022-06-04 09:50:20
引言: 在现代的网络应用程序中,进行HTTP请求是一项常见的任务。Apache HttpClient是一个功能强大且广泛使用的Java库,它提供了方便的方法来执行HTTP请求并处理响应。本文将介绍如何使用HttpClient库进行HTTP请求,包括GET请求、POST请求、添加参数和请求体、设置请求头等操作。
HttpClient简介: HttpClient是一个开源的Java库,用于处理HTTP通信。它提供了各种类和方法,使得执行HTTP请求变得简单而直观。HttpClient不仅支持基本的HTTP协议功能,还提供了更高级的功能,如连接管理、cookie管理、代理设置等。
导入HttpClient库
在使用HttpClient之前,需要在项目中导入HttpClient库。可以通过在Maven项目的pom.xml文件中添加以下依赖项来实现:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
发起GET请求
GET请求是获取服务器资源的一种常见方式。下面是使用HttpClient进行GET请求的示例代码:
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
CloseableHttpResponse response = client.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
在上述代码中,我们创建了一个HttpGet对象,并传入要请求的URL。然后使用HttpClient的execute
方法发送请求并获取响应。最后,通过EntityUtils
将响应内容转换为字符串并进行输出。
发起POST请求
POST请求用于向服务器提交数据。下面是使用HttpClient进行POST请求的示例代码:
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
与GET请求相比,POST请求的代码几乎相同。只需将HttpGet
替换为HttpPost
即可。
添加请求参数
有时候我们需要在请求中添加参数。使用HttpClient的URIBuilder
类可以方便地构建带有参数的URL。下面是一个示例:
URIBuilder builder = new URIBuilder("http://httpbin.org/post");
builder.addParameter("name", "Ru");
builder.addParameter("age", "18");
URI uri = builder.build();
HttpPost httpPost = new HttpPost(uri);
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
在上述代码中,我们创建了一个URIBuilder
对象,并使用addParameter
方法添加了两个参数。然后通过build
方法生成最终的URI,将其传递给HttpPost
对象进行请求。
设置请求体
有时候我们需要在POST请求中添加请求体,通常使用JSON格式进行数据传输。下面是一个示例:
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
String jsonBody = "{"name": "Ru", "age": 18}";
// 设置请求头部信息
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
StringEntity requestEntity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
}
在上述代码中,我们首先设置了请求的Content-Type为application/json,然后创建了一个StringEntity对象来封装请求体数据。将其设置为HttpPost对象的实体,并执行请求。最后,通过EntityUtils将响应体转换为字符串并进行输出。
设置请求头
有时候我们需要在请求中添加自定义的请求头信息,如User-Agent、Authorization等。下面是一个示例:
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
httpGet.setHeader("User-Agent", "MyHttpClient/1.0");
httpGet.setHeader("Authorization", "Bearer my_token");
CloseableHttpResponse response = client.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
在上述代码中,我们使用setHeader
方法设置了两个自定义的请求头信息,然后执行GET请求并输出响应结果。
完整demo:
package org.example.TestMaven;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class HttpClientDemo {
static CloseableHttpClient client = HttpClients.createDefault();
public static void main(String[] args) throws IOException, URISyntaxException {
// httpGetDemo();
// httpPostDemo();
// httpParamsDemo();
// httpBodyDemo();
httpHeaderDemo();
}
public static void httpGetDemo() throws IOException {
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
CloseableHttpResponse response = client.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
}
public static void httpPostDemo() throws IOException {
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
}
public static void httpParamsDemo() throws IOException, URISyntaxException {
URIBuilder builder = new URIBuilder("http://httpbin.org/post");
builder.addParameter("name", "Ru");
builder.addParameter("age", "18");
URI uri = builder.build();
HttpPost httpPost = new HttpPost(uri);
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
}
public static void httpBodyDemo() throws IOException {
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
String jsonBody = "{"name": "Ru", "age": 18}";
// 设置请求头部信息
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
StringEntity requestEntity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
}
}
public static void httpHeaderDemo() throws IOException {
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
httpGet.setHeader("User-Agent", "MyHttpClient/1.0");
httpGet.setHeader("Authorization", "Bearer my_token");
CloseableHttpResponse response = client.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
结论: 本文介绍了如何使用HttpClient库进行HTTP请求的常见操作,包括GET请求、POST请求、添加请求参数和请求体、设置请求头等。通过使用HttpClient,我们可以轻松地与服务器进行通信并处理响应数据。希望本文对你理解和使用HttpClient有所帮助!
来源:https://juejin.cn/post/7234342980156915769


猜你喜欢
- Java goto语句妙用今天和朋友聊天的时候,无意间聊到了 goto 语句,但是在 Java 中, goto 是保留关键字,但是朋友说 J
- 枚举类型是一种的值类型,它用于声明一组命名的常数。(1)枚举的声明:枚举声明用于声明新的枚举类型。访问修辞符 enum 枚举名:基础类型&n
- Spring @Async无法实现异步问题原因项目中存在2个配置文件:springMVC.xml和beanDefines.xml,它们都配置
- *注:可以用 adb logcat > 路径/文件名 来保存,此命令执行之时起的全部日志信息到一个文件里,ctrl + C 结束日志输
- Android9.0无法通过以下两种方式实现静默安装:1.runtime执行shell cmd2.PackageInstall 反射机制但是
- 实例如下所示:System.Net.WebClient myWebClient = new System.Net.WebClient();
- 先说结论:字段类型更改为 'keyword'elasticSearch官方文档中创建index代码如下PUT /my_sto
- Android 如何修改APK的默认名称用Android Studio 打包App时生成的名称默认是 app-release.apk(已签名
- RecyclerView上拉加载,先看效果:网上有很多这类得框架,不过在自己的项目只用到上拉加载的功能,所以自己封装一个简单点的。主要依赖B
- @Entity和@Table注解的用法@Entity注解@Entity注解和@Table注解都是Java Persistence API中定
- http interface从 Spring 6 和 Spring Boot 3 开始,Spring 框架支持将远程 HTTP 服务代理成带
- 本文实例讲述了C#对list列表进行随机排序的方法。分享给大家供大家参考。具体实现方法如下:public List<T> Ran
- java 代码块与静态代码块加载顺序public abstract class ClassLoadingTest {public stati
- 根据狂神的视频做的,然后自己优化了一些bug,比如新生成食物的时候不会生成在蛇的身体上,再新增长身体的时候不会在左上角出现一个绿色的方块以及
- 一、简介Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。Spring Cache提供
- 限流器算法目前常用限流器算法为两种:令牌桶算法和漏桶算法,主要区别在于:漏桶算法能够强行限制请求速率,平滑突发请求,而令牌桶算法在限定平均速
- 一、Override首先,@Override 注解是伪代码,表示子类重写父类的方法。这个注解不写也是可以的,但是写了有如下好处:1. 可以当
- Java中的main函数的详细介绍JAVA中的主函数是我们再熟悉不过的了,相信每个学习过JAVA语言的人都能够熟练地写出这个程序的入口函数,
- checked 和 unchecked关键字用来限定检查或者不检查数学运算溢出的;如果使用了checked发生数学运算溢出时会抛出Overf
- 一.hutool工具摘抄一段hutool工具的简介:Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,