Apache HttpClient HTML表单POST请求示例

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

在这篇快速文章中,我们将讨论如何使用Apache HttpClient 4.5+来处理HTML表单。

使用HTML表单

许多应用程序需要模拟提交HTML表单的过程,例如,为了登录一个Web应用程序或提交输入数据,HttpClient提供了实体类UrlEncodedFormEntity来促进这一过程。

List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);

UrlEncodedFormEntity实例将使用所谓的URL编码对参数进行编码并产生以下内容:

param1=value1&param2=value2

HttpClient支持HTTP/1.1规范中定义的所有HTTP方法:GETHEADPOSTPUTDELETETRACEOPTIONS。每个方法类型都有一个特定的类:HttpGetHttpHeadHttpPostHttpPutHttpDeleteHttpTraceHttpOptions
在这个例子中,我们将使用HttpPost类来处理POST HTTP方法。

使用Apache HttpClient--Maven依赖性

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

我们使用maven来管理我们的依赖,并使用Apache HttpClient 4.5版本。在你的项目中添加以下依赖项。

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

开发步骤

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

CloseableHttpClient httpclient = HttpClients.createDefault()

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

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

HttpPost httpPost = new HttpPost("http://httpbin.org/post");

3. 准备好表单对象

List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("John", "Cena"));
form.add(new BasicNameValuePair("Tom", "Cruise"));
form.add(new BasicNameValuePair("tony", "stark"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8);

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

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(httpPost, responseHandler);

提交HTML表单参数

在下面的例子中,我们向资源http://httpbin.org/post发布HTML表单参数。这个资源会确认数据并返回一个JSON对象,我们将简单地将其打印到控制台。当发送HTML表单参数时,你通常应该将内容类型设置为application/x-www-form-urlencoded,但Apache HttpClient会自动检测内容类型并进行相应设置。

package com.javadevelopersguide.httpclient.examples;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* This example demonstrates the use of {@link HttpPost} request method. And
* sending HTML Form request parameters
*/
public class HttpClientHttpFormExample {

    public static void main(String...args) throws IOException {

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            List < NameValuePair > form = new ArrayList < > ();
            form.add(new BasicNameValuePair("John", "Cena"));
            form.add(new BasicNameValuePair("Tom", "Cruise"));
            form.add(new BasicNameValuePair("tony", "stark"));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8);

            HttpPost httpPost = new HttpPost("http://httpbin.org/post");
            httpPost.setEntity(entity);
            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 responseEntity = response.getEntity();
                    return responseEntity != null ? EntityUtils.toString(responseEntity) : 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": "", 
  "files": {}, 
  "form": {
    "John": "Cena", 
    "Tom": "Cruise", 
    "tony": "stark"
  }, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "31", 
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", 
    "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/post"
}

相关文章