当前位置: 首页 > 教程 > HttpClient >

HttpClient HTTP POST请求方法示例

精华
小牛编辑
88浏览
2023-03-14

本教程演示如何使用Apache HttpClient 4.5发出Http POST请求。 HTTP POST请求方法请求服务器接受请求中包含的实体作为URI标识的Web资源。 发布的数据可以是但不限于现有资源的注释或数据格式化的JSON,XML或提交的表单数据。 服务器可以使用发布的数据来更新数据库中的资源,或处理这些数据。

Maven依赖关系

我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中,以便创建HTTP POST请求方法。

pom.xml 文件的内容如下 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

HTTP GET请求方法示例

在以下示例中,我们将数据发布到资源URL:http://httpbin.org/post 。 该资源确认数据并返回一个JSON对象,我们只需将其打印到控制台。 注意:使用Java7try-with-resources来自动处理关闭ClosableHttpClient。 接下来使用Java 8lambda作为ResponseHandler。 在这里,根据Http状态代码判断返回状态,当一切正常时,我们会将解析的响应正文返回给String。 当状态码不是所期望的时候,将抛出一个ClientProtocolException,表明Http POST请求方法失败。 最后,我们将响应主体打印到控制台。

文件:HttpPostRequestMethodExample.java -

package com.yiibai.httpdemo;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
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;
import java.io.IOException;

/**
 * This example demonstrates the use of {@link HttpPost} request method.
 */
public class HttpPostRequestMethodExample {

    public static void main(String... args) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("http://httpbin.org/post");
            httpPost.setEntity(new StringEntity("Hello, World"));

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

执行上面示例代码,得到以下结果 -

Executing request POST http://httpbin.org/post 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.5 (Java/1.8.0_65)"
  }, 
  "json": null, 
  "origin": "112.67.161.222", 
  "url": "http://httpbin.org/post"
}