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"
}