广告位联系
返回顶部
分享到

使用Apache HttpClient执行GET、POST、PUT和DELETE请求的操作方法

linux 来源:互联网 作者:佚名 发布时间:2024-12-11 22:36:33 人浏览
摘要

Apache HttpClient 是一个功能强大且灵活的库,用于在Java中处理HTTP请求。 它支持多种HTTP方法,包括GET、POST、PUT和DELETE等。 本教程将演示如何使用Apache HttpClient来执行GET、POST、PUT和DELETE请求。

Apache HttpClient 是一个功能强大且灵活的库,用于在Java中处理HTTP请求。

它支持多种HTTP方法,包括GET、POST、PUT和DELETE等。

本教程将演示如何使用Apache HttpClient来执行GET、POST、PUT和DELETE请求。

Maven依赖

要使用Apache HttpClient,您需要在pom.xml文件中添加以下依赖项:

1

2

3

4

5

6

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->

<dependency>

    <groupId>org.apache.httpcomponents.client5</groupId>

    <artifactId>httpclient5</artifactId>

    <version>5.3</version>

</dependency>

示例场景

我们将创建简单的Java类,这些类将向指定的URL发送GET、POST、PUT和DELETE请求,并打印响应。

JSONPlaceholder API

为了演示目的,我们将使用JSONPlaceholder API,该API提供了一个虚拟的在线RESTful端点,用于测试和原型设计。

GET请求

发送GET请求的Java类

创建一个名为HttpClientGetExample的类,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import org.apache.hc.client5.http.classic.methods.HttpGet;

import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;

import org.apache.hc.client5.http.impl.classic.HttpClients;

import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpClientGetExample {

    public static void main(String[] args) {

        String url = "https://jsonplaceholder.typicode.com/posts/1";

        // 创建HttpClient

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建HttpGet请求

            HttpGet request = new HttpGet(url);

            // 执行请求

            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // 获取HTTP响应状态

                System.out.println("Response Code: " + response.getCode());

                // 获取HTTP响应内容

                String content = EntityUtils.toString(response.getEntity());

                System.out.println("Response Content: \n" + content);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

示例输出

Response Code: 200
Response Content: 
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

POST请求

发送POST请求的Java类

创建一个名为HttpClientPostExample的类,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

import org.apache.hc.client5.http.classic.methods.HttpPost;

import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;

import org.apache.hc.client5.http.impl.classic.HttpClients;

import org.apache.hc.core5.http.io.entity.StringEntity;

import org.apache.hc.core5.http.ContentType;

import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpClientPostExample {

    public static void main(String[] args) {

        String url = "https://jsonplaceholder.typicode.com/posts";

        String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

        // 创建HttpClient

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建HttpPost请求

            HttpPost request = new HttpPost(url);

            // 设置JSON负载

            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

            request.setEntity(entity);

            // 设置头部

            request.setHeader("Accept", "application/json");

            request.setHeader("Content-type", "application/json");

            // 执行请求

            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // 获取HTTP响应状态

                System.out.println("Response Code: " + response.getCode());

                // 获取HTTP响应内容

                String content = EntityUtils.toString(response.getEntity());

                System.out.println("Response Content: \n" + content);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

示例输出

Response Code: 201
Response Content: 
{
  "title": "foo",
  "body": "bar",
  "userId": 1,
  "id": 101
}

PUT请求

发送PUT请求的Java类

创建一个名为HttpClientPutExample的类,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

import org.apache.hc.client5.http.classic.methods.HttpPut;

import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;

import org.apache.hc.client5.http.impl.classic.HttpClients;

import org.apache.hc.core5.http.io.entity.StringEntity;

import org.apache.hc.core5.http.ContentType;

import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpClientPutExample {

    public static void main(String[] args) {

        String url = "https://jsonplaceholder.typicode.com/posts/1";

        String json = "{\"id\":1,\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

        // 创建HttpClient

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建HttpPut请求

            HttpPut request = new HttpPut(url);

            // 设置JSON负载

            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

            request.setEntity(entity);

            // 设置头部

            request.setHeader("Accept", "application/json");

            request.setHeader("Content-type", "application/json");

            // 执行请求

            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // 获取HTTP响应状态

                System.out.println("Response Code: " + response.getCode());

                // 获取HTTP响应内容

                String content = EntityUtils.toString(response.getEntity());

                System.out.println("Response Content: \n" + content);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

示例输出

Response Code: 200
Response Content: 
{
  "id": 1,
  "title": "foo",
  "body": "bar",
  "userId": 1
}

DELETE请求

发送DELETE请求的Java类

创建一个名为HttpClientDeleteExample的类,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import org.apache.hc.client5.http.classic.methods.HttpDelete;

import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;

import org.apache.hc.client5.http.impl.classic.HttpClients;

import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpClientDeleteExample {

    public static void main(String[] args) {

        String url = "https://jsonplaceholder.typicode.com/posts/1";

        // 创建HttpClient

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建HttpDelete请求

            HttpDelete request = new HttpDelete(url);

            // 执行请求

            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // 获取HTTP响应状态

                System.out.println("Response Code: " + response.getCode());

                // 获取HTTP响应内容

                String content = EntityUtils.toString(response.getEntity());

                System.out.println("Response Content: \n" + content);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

示例输出

Response Code: 200
Response Content: 
{}

额外配置

  • 设置自定义头部:可以通过调用请求对象(如HttpGet、HttpPost、HttpPut、HttpDelete)上的setHeader方法来设置自定义头部。
  • 处理重定向:默认情况下,Apache HttpClient会自动处理重定向。您可以使用自定义的HttpClientBuilder来自定义这种行为。
  • 设置超时:可以使用RequestConfig来设置连接和套接字超时。

结论

使用Apache HttpClient来执行GET、POST、PUT和DELETE HTTP请求非常方便。

通过遵循本教程,您现在应该能够创建并执行这些类型的请求,处理响应,并定制HTTP请求和响应过程。

Apache HttpClient提供了一整套功能,使其成为处理Java应用程序中HTTP操作的优秀选择。

JSONPlaceholder API作为一个实用且方便的来源,适合用来测试和原型化您的HTTP请求。


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计