HttpClient HTML表單提交範例


許多應用程式需要模擬提交HTML表單的過程,以便登入到Web應用程式或提交輸入資料。 HttpClient提供實體類UrlEncodedFormEntity來促進該過程。 以下教學顯示了如何使用apache HttpClient 4.5傳送HTML表單引數。

Maven依賴關係

我們使用maven來管理依賴關係,並使用Apache HttpClient 4.5版本。 將以下依賴項新增到您的專案中。

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>

提交HTML表單引數範例

在以下範例中,我們將HTML表單引數發布到資源: http://httpbin.org/post 。 該資源確認資料並返回一個JSON物件,只需將其列印到控制台。 傳送HTML表單引數時,通常應將內容型別設定為application/x-www-form-urlencoded,但Apache HttpClient會自動檢測內容型別並相應地設定它。

檔案:HttpClientHttpFormExample.java -

package com.yiibai.httpdemo;

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("foo", "bar"));
            form.add(new BasicNameValuePair("employee", "maxsu"));
            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": {
    "employee": "maxsu", 
    "foo": "bar"
  }, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "22", 
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5.5 (Java/1.8.0_65)"
  }, 
  "json": null, 
  "origin": "112.67.166.104", 
  "url": "http://httpbin.org/post"
}