`
a137268431
  • 浏览: 146311 次
文章分类
社区版块
存档分类
最新评论

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提交方式

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

二、Form表单Post提交方式

01 DefaultHttpClient httpclient =newDefaultHttpClient();
02 try{
03 HttpPost httpost =newHttpPost("http://www.xxx.com/x.jsp?");
04 List <NameValuePair> nvps =newArrayList <NameValuePair>();
05 //提交两个参数及值
06 nvps.add(newBasicNameValuePair("age","20"));
07 nvps.add(newBasicNameValuePair("username","张三"));
08 //设置表单提交编码为UTF-8
09 httpost.setEntity(newUrlEncodedFormEntity(nvps, HTTP.UTF_8));
10 HttpResponse response = httpclient.execute(httpost);
11 HttpEntity entity = response.getEntity();
12 System.out.println("Login form get: "+ response.getStatusLine());
13 EntityUtils.consume(entity);
14 }finally{
15 // When HttpClient instance is no longer needed,
16 // shut down the connection manager to ensure
17 // immediate deallocation of all system resources
18 httpclient.getConnectionManager().shutdown();
19 }

在提交到的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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics