HttpClient是一款用Java写的很是好用的基于Http协议的客户端编程工具包。具体举例来说,用它能够模拟form表单提交数据动做,能够模拟访问网页动做及获得网页源码内容等等,这两点或许是咱们在工做中最经常使用到的。 html
这里也主要是以介绍模拟form表单提交数据来介绍一下HttpClient,准确地讲主要是4.x版本,由于我发如今平常中,HttpClient的使用都仍是使用3.x的版本,而如今HttpClient的官网上,都已是最新版本4.1.3了,3.x版本在官网不见丝毫踪迹,进入到下载页面也见不着3.x版本的下载。 java
HttpClient对于使用者而言,一个很是大的好处就是它的例子很是丰富,几乎每一个功能都有对应的例子代码,这里讲的模拟form表单提交数据也是来源于HttpClient自带的例子。 apache
1、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(); }
2、Form表单Post提交方式 jsp
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/ post
关于HttpClient的例子页面,见: 编码
http://hc.apache.org/httpcomponents-client-ga/examples.html spa
或者在下载后的目录: code
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