服务器 > 网络 > https

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

94人参与 2024-12-11 https

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: 
{}

额外配置

结论

使用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请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

安装、配置和验证FTP服务器的步骤

12-11

nginx如何根据报文里字段转发至不同地址

12-11

Nginx设置HTTPS监听的具体步骤

12-17

使用nginx正向代理实现访问外网

12-17

Apache HTTP 服务器的安全配置指南(最新推荐)

12-18

Nginx HttpHeader增加几个关键的安全选项问题小结

12-08

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论