Apache HttpClient PUT HTTP请求示例

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

在这篇快速文章中,我们将逐步讨论如何使用Apache HttpClient 4.5来进行HTTP PUT请求。HTTP PUT请求方法要求服务器接受并存储所提供的URI中包含的实体。如果URI指向一个已经存在的资源,它将被修改;如果URI没有指向一个现有的资源,那么服务器可以用该URI创建资源。
HttpClient支持HTTP/1.1规范中定义的所有HTTP方法:GETHEADPOSTPUTDELETETRACEOPTIONS。每种方法类型都有一个特定的类:HttpGetHttpHeadHttpPostHttpPutHttpDeleteHttpTrace、和HttpOptions
在这个例子中,我们将使用HttpPut类来处理PUT HTTP方法。

使用Apache HttpClient

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

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

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

开发步骤

让我们创建一个逐步的例子,使用HttpClient制作一个HTTP PUT请求。

1. 使用辅助类HttpClients创建CloseableHttpClient的实例。

CloseableHttpClient httpclient = HttpClients.createDefault()

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

2. 创建一个基本的PUT请求

HttpPut httpPut = new HttpPut("http://localhost:8080/api/v1/users/5");

3. 为PUT HTTP请求添加头信息

HttpPut httpPut = new HttpPut("http://localhost:8080/api/v1/users/5");
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");

4. 在PUT请求中添加JSON数据

String json = "{\r\n" + 
  "  \"firstName\": \"Ram\",\r\n" + 
  "  \"lastName\": \"Jadhav\",\r\n" + 
  "  \"emailId\": \"ramesh1234@gmail.com\",\r\n" + 
  "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + 
  "  \"createdBy\": \"Ramesh\",\r\n" + 
  "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + 
  "  \"updatedby\": \"Ramesh\"\r\n" + 
  "}";
StringEntity stringEntity = new StringEntity(json);
httpPut.setEntity(stringEntity);

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);
    }
};

6. 通过execute()方法发送一个基本的POST请求

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

HttpClient HTTP PUT请求方法实例

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

在下面的例子中,我们发送一个资源给http://localhost:8080/api/v1/users/5。这个资源接受请求的JSON,对其进行处理并将其存储到数据库中。这个服务也会返回一个带有更新资源的响应。在这个例子中,我们使用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.HttpPut;
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;

/**
* This example demonstrates the use of {@link HttpPut} request method.
* @author Ramesh Fadatare
*/

public class PUTRequestExample {

    public static void main(String[] args) throws IOException {
        putUser();
    }

    public static void putUser() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPut httpPut = new HttpPut("http://localhost:8080/api/v1/users/5");
            httpPut.setHeader("Accept", "application/json");
            httpPut.setHeader("Content-type", "application/json");
            String json = "{\r\n" + "  \"firstName\": \"Ram\",\r\n" + "  \"lastName\": \"Jadhav\",\r\n" +
                "  \"emailId\": \"ramesh1234@gmail.com\",\r\n" +
                "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + "  \"createdBy\": \"Ramesh\",\r\n" +
                "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + "  \"updatedby\": \"Ramesh\"\r\n" +
                "}";
            StringEntity stringEntity = new StringEntity(json);
            httpPut.setEntity(stringEntity);

            System.out.println("Executing request " + httpPut.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(httpPut, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

输出

Executing request PUT http://localhost:8080/api/v1/users/5 HTTP/1.1
----------------------------------------
{"id":5,"firstName":"Ram","lastName":"Jadhav","emailId":"ramesh1234@gmail.com",
"createdAt":"2018-09-11T11:19:56.000+0000","createdBy":"Ramesh",
"updatedAt":"2018-10-29T09:43:13.756+0000","updatedby":"Ramesh"}

更多的例子

在下面的例子中,我们将数据放入资源http://httpbin.org/put。这个资源确认了数据并返回一个JSON对象,我们将简单地将其打印到控制台。

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.HttpPut;
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;

/**
* This example demonstrates the use of {@link HttpPut} request method.
* 
* @author Ramesh Fadatare
*/

public class PUTRequestExample {

    public static void main(String[] args) throws IOException {
        put();
    }

    public static void put() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPut httpPut = new HttpPut("http://httpbin.org/put");
            httpPut.setEntity(new StringEntity("Hello, World"));

            System.out.println("Executing request " + httpPut.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(httpPut, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }

}

输出

Executing request PUT http://httpbin.org/put HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "data": "Hello, World", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "12", 
    "Content-Type": "text/plain; charset=ISO-8859-1", 
    "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/put"
}

相关文章