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,HttpClient,http,请求
0
投稿

猜你喜欢

  • java 创建线程的四种方式

    2023-11-02 21:38:07
  • 关于springboot中对sqlSessionFactoryBean的自定义

    2022-12-09 06:05:09
  • spring boot如何使用POI读取Excel文件

    2022-09-19 21:26:33
  • java实现简易外卖订餐系统

    2021-11-04 16:01:25
  • SpringBoot整合Quartz实现定时任务详解

    2021-11-22 06:40:57
  • 解析spring cloud ouath2中的Eureka

    2023-10-12 04:07:54
  • java实现简单的图书管理系统

    2022-11-25 03:30:11
  • Spring Boot实现分布式系统中的服务发现和注册(最新推荐)

    2022-07-10 03:50:23
  • 浅谈java的接口和C++虚类的相同和不同之处

    2023-08-05 12:01:51
  • 使用Feign传递请求头信息(Finchley版本)

    2023-06-07 22:38:07
  • Unity Shader实现黑幕过场效果

    2022-01-13 00:18:10
  • Java实现将图片上传到webapp路径下 路径获取方式

    2023-07-10 12:44:13
  • C#实现观察者模式(Observer Pattern)的两种方式

    2023-06-20 21:05:18
  • Java Redis Redisson配置教程详解

    2022-10-13 06:32:39
  • Java Spring处理循环依赖详解

    2022-07-14 05:06:16
  • Scala中的mkString的具体使用方法

    2023-11-16 00:18:18
  • 详解利用spring-security解决CSRF问题

    2023-07-31 14:31:19
  • Android仿新浪微博分页管理界面(3)

    2023-08-04 19:14:02
  • 深入了解Java接口回调机制

    2023-11-09 15:52:05
  • Android 如何获取手机总内存和可用内存等信息

    2023-07-27 13:11:42
  • asp之家 软件编程 m.aspxhome.com