Apache HttpClient DELETE HTTP请求示例

x33g5p2x  于2022-10-07 转载在 Apache  
字(5.3k)|赞(0)|评价(0)|浏览(671)

在这篇快速文章中,我们将逐步讨论如何使用Apache HttpClient 4.5来进行HTTP DELETE请求。HTTP DELETE请求方法请求删除由URI指定的资源。

HttpClient支持HTTP/1.1规范中定义的所有HTTP方法:GETHEADPOSTPUTDELETETRACEOPTIONS。每种方法类型都有一个特定的类:HttpGetHttpHeadHttpPostHttpPutHttpDeleteHttpTrace、和HttpOptions
在这个例子中,我们将使用HttpDelete类来处理DELETE HTTP方法。

使用Apache HttpClient

Apache HttpClient库允许处理HTTP请求。要使用这个库,需要在你的Maven或Gradle构建文件中添加一个依赖项。你可以在这里找到最新版本:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

我们使用maven来管理我们的依赖,并使用Apache HttpClient 4.5版。在你的项目中添加以下依赖,以便使HTTP DELETE请求方法。

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.5</version>
</dependency>

开发步骤

让我们创建一个逐步的例子,使用HttpClient来进行一个Http DELETE请求。

使用帮助类HttpClients创建CloseableHttpClient的实例。

CloseableHttpClient httpclient = HttpClients.createDefault()

HttpClients.createDefault()方法创建具有默认配置的CloseableHttpClient实例。

创建基本的DELETE请求

HttpDelete httpDelete = new HttpDelete("http://localhost:8080/api/v1/users/5");

创建一个自定义的响应处理程序

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

通过execute()方法发送基本的POST请求

String responseBody = httpclient.execute(httpDelete, responseHandler);

HttpClient HTTP DELETE请求方法实例

让我们来讨论如何在实时项目中使用HttpClient。考虑到我们已经部署了Spring Boot Restful CRUD APIs。请看这篇文章 - Spring Boot 2 + hibernate 5 + CRUD REST API教程。

在下面的例子中,我们使用http://localhost:8080/api/v1/users/5 Rest service从id为5的数据库中删除一个用户。 在这个例子中,我们使用Java 7 try-with-resources来自动处理ClosableHttpClient的关闭,我们也使用Java 8 lambdas处理ResponseHandler

package com.javadevelopersguide.httpclient.examples;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
* This example demonstrates the use of {@link HttpDelete} request method.
* 
* @author Ramesh Fadatare
*/
public class DELETERequestExample {
    public static void main(String[] args) throws IOException {
        deleteUser();
    }

    public static void deleteUser() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            HttpDelete httpDelete = new HttpDelete("http://localhost:8080/api/v1/users/5");
            System.out.println("Executing request " + httpDelete.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpDelete, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

输出

Executing request DELETE http://localhost:8080/api/v1/users/5 HTTP/1.1
----------------------------------------
{"deleted":true}

更多的例子

在下面的例子中,我们通过对以下资源进行HTTP删除请求方法来演示HTTP Delete请求方法:http://httpbin.org/delete

package com.javadevelopersguide.httpclient.examples;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
* This example demonstrates the use of {@link HttpDelete} request method.
* 
* @author Ramesh Fadatare
*/
public class DELETERequestExample {
    public static void main(String[] args) throws IOException {
        delete();
    }

    public static void delete() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            HttpDelete httpDelete = new HttpDelete("http://httpbin.org/delete");

            System.out.println("Executing request " + httpDelete.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpDelete, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

输出

Executing request DELETE http://httpbin.org/delete HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "0", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
  }, 
  "json": null, 
  "origin": "49.35.12.218", 
  "url": "http://httpbin.org/delete"
}

相关文章