在这篇快速文章中,我们将讨论如何使用Apache HttpClient 4.5+来处理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¶m2=value2
HttpClient
支持HTTP/1.1规范中定义的所有HTTP方法:GET
、HEAD
、POST
、PUT
、DELETE
、TRACE
和OPTIONS
。每个方法类型都有一个特定的类:HttpGet
、HttpHead
、HttpPost
、HttpPut
、HttpDelete
、HttpTrace
和HttpOptions
。
在这个例子中,我们将使用HttpPost
类来处理POST HTTP方法。
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>
CloseableHttpClient httpclient = HttpClients.createDefault()
HttpClients.createDefault()
方法以默认配置创建CloseableHttpClient
实例。
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
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);
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);
在下面的例子中,我们向资源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"
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/10/apache-httpclient-html-form-post-request-example.html
内容来源于网络,如有侵权,请联系作者删除!