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 = new DefaultHttpClient(); |
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()); |
10 | EntityUtils.consume(entity); |
15 | httpclient.getConnectionManager().shutdown(); |
二、Form表单Post提交方式
01 | DefaultHttpClient httpclient = new DefaultHttpClient(); |
03 | HttpPost httpost = new HttpPost( "http://www.xxx.com/x.jsp?" ); |
04 | List <NameValuePair> nvps = new ArrayList <NameValuePair>(); |
06 | nvps.add( new BasicNameValuePair( "age" , "20" )); |
07 | nvps.add( new BasicNameValuePair( "username" , "张三" )); |
09 | httpost.setEntity( new UrlEncodedFormEntity(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); |
18 | 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