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

 更新时间:2024年12月10日 16:46:20   作者:疯一样的码农  
Apache HttpClient 是一个功能强大且灵活的库,用于在Java中处理HTTP请求,本教程将演示如何使用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文件中添加以下依赖项:

<!-- 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的类,代码如下:

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的类,代码如下:

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的类,代码如下:

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的类,代码如下:

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请求。

到此这篇关于如何使用Apache HttpClient来执行GET、POST、PUT和DELETE请求的文章就介绍到这了,更多相关Apache HttpClient执行GET、POST、PUT和DELETE请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Linux基础命令之mktemp详解

    Linux基础命令之mktemp详解

    创建临时文件或者目录,这样的创建方式是安全的。此命令的适用范围:RedHat、RHEL、Ubuntu、CentOS、SUSE、openSUSE、Fedora。这篇文章主要介绍了Linux基础命令之mktemp ,需要的朋友可以参考下
    2018-10-10
  • 浅谈生产者消费者模型(Linux系统下的两种实现方法)

    浅谈生产者消费者模型(Linux系统下的两种实现方法)

    下面小编就为大家带来一篇浅谈生产者消费者模型(Linux系统下的两种实现方法)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01
  • centos 6.8命令行下使用pptpsetup进行pptp拨号的实现方法

    centos 6.8命令行下使用pptpsetup进行pptp拨号的实现方法

    centos 6.8 命令行下可使用pptpsetup进行pptp拨号,首先安装ppp,pptp和pptp-setup三个包,使用pptpsetup进行连接,下面给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2016-10-10
  • crontab定时任务不执行的一些原因总结

    crontab定时任务不执行的一些原因总结

    这篇文章主要给大家总结介绍了关于crontab定时任务不执行的一些原因,对每种可能发生的原因都给出了解决方法,对遇到这个问题的朋友们具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-01-01
  • linux解决ping通但端口不通的问题

    linux解决ping通但端口不通的问题

    在本文里我们给大家整理了关于在linux解决ping通但端口不通的问题的解决方法和步骤,有需要的朋友们参考下。
    2018-09-09
  • Linux修改pip临时目录方法的详解

    Linux修改pip临时目录方法的详解

    在Linux系统中,pip 在安装 Python 包时会使用临时目录(TMPDIR),但默认的临时目录可能会受到存储空间不足或权限问题的影响,所以本文将详细介绍如何修改 pip 的临时目录,并提供相关的背景知识和实用建议,需要的朋友可以参考下
    2025-03-03
  • CentOS7设置定时任务

    CentOS7设置定时任务

    工作中需要开启一个定时任务,经过一番研究,最终方案如下,这里分享给大家
    2018-08-08
  • linux下使用cmake编译安装mysql的详细教程

    linux下使用cmake编译安装mysql的详细教程

    这篇文章主要介绍了linux下使用cmake编译安装mysql的详细教程,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-10-10
  • CentOS7环境下gcc(版本10.2.0)升级详细过程

    CentOS7环境下gcc(版本10.2.0)升级详细过程

    大家好,本篇文章主要讲的是CentOS7环境下gcc(版本10.2.0)升级详细过程,感兴趣的同学快来看一看吧,希望对你有帮助
    2021-11-11
  • CentOS7 + node.js + nginx + MySQL搭建服务器全过程

    CentOS7 + node.js + nginx + MySQL搭建服务器全过程

    这篇文章主要介绍了关于CentOS7 + node.js + nginx + MySQL搭建服务器的全过程,文章通过一步步的步骤进行介绍的很详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
    2017-03-03

最新评论