HttpClient4.x:Get和Post提交数据

HttpClient是一款用Java写的非常好用的基于Http协议的客户端编程工具包。具体举例来讲,用它可以模拟form表单提交数据动作,可以模拟访问网页动作及得到网页源码内容等等,这两点或许是我们在工作中最常用到的。

这里也主要是以介绍模拟form表单提交数据来介绍一下HttpClient,准确地讲主要是4.x版本,因为我发现在日常中,HttpClient的使用都还是使用3.x的版本,而现在HttpClient的官网上,都已经是最新版本4.1.3了,3.x版本在官网不见丝毫踪影,进入到下载页面也见不着3.x版本的下载。

HttpClient对于使用者而言,一个非常大的好处就是它的例子非常丰富,几乎每个功能都有对应的例子代码,这里讲的模拟form表单提交数据也是来源于HttpClient自带的例子。

一、Get提交方式

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
//注:如果参数值为中文的话,提交过去后可能会是乱码
HttpGet httpget = new
HttpGet("http://www.xxx.com/x.jsp?username=zhangsan&age=20");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
//如果entity是流数据则关闭之
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}

二、Form表单Post提交方式

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpost = new HttpPost("http://www.xxx.com/x.jsp?");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
//提交两个参数及值
nvps.add(new BasicNameValuePair("age", "20"));
nvps.add(new BasicNameValuePair("username", "张三"));
//设置表单提交编码为UTF-8
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}

在提交到的x.jsp中,我们还是像平常获取一个form表单数据那样处理就行了:

String username = request.getParameter("username");

 

HttpClient官方网址:http://hc.apache.org/

关于HttpClient的例子页面,见:

http://hc.apache.org/httpcomponents-client-ga/examples.html

或者在下载后的目录:

httpcomponents-client-4.1.3_src\httpclient\src\examples 。

目前HttpClient分两部分,一部分是HttpClient,另一部分是HttpCore,两者都要下载下来,上面的例子见:

httpcomponents-client-4.1.3_src\httpclient\src\examples\org\apache\http\examples\client\ClientFormLogin.java

你可能感兴趣的:(get,post,httpclient4)