打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
httpclient教程
Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。


1. 读取网页(HTTP/HTTPS)内容

   最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面

Java代码
  1. package http.demo;   
  2.   
  3. import java.io.IOException;   
  4. import org.apache.commons.httpclient.*;   
  5. import org.apache.commons.httpclient.methods.*;   
  6.   
  7. public class SimpleClient {   
  8.   
  9.     public static void main(String[] args) throws IOException   
  10.     {   
  11.         HttpClient client = new HttpClient();      
  12.   
  13.         //设置代理服务器地址和端口       
  14.   
  15.         //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);   
  16.   
  17.         //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https   
  18.   
  19.         HttpMethod method = new GetMethod("http://java.sun.com");   
  20.   
  21.         //使用POST方法   
  22.   
  23.         //HttpMethod method = new PostMethod("http://java.sun.com");   
  24.   
  25.         client.executeMethod(method);   
  26.   
  27.         //打印服务器返回的状态   
  28.   
  29.         System.out.println(method.getStatusLine());   
  30.   
  31.         //打印返回的信息   
  32.   
  33.         System.out.println(method.getResponseBodyAsString());   
  34.   
  35.         //释放连接   
  36.   
  37.         method.releaseConnection();   
  38.   
  39.     }   
  40. }  


2. 以GET或者POST方式向网页提交参数


Java代码
  1. package http.demo;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import org.apache.commons.httpclient.*;   
  6.   
  7. import org.apache.commons.httpclient.methods.*;   
  8.   
  9. /**  
  10.  
  11. * 提交参数演示  
  12.  
  13. * 该程序连接到一个用于查询手机号码所属地的页面  
  14.  
  15. * 以便查询号码段1330227所在的省份以及城市  
  16.  
  17. */  
  18.   
  19. public class SimpleHttpClient {   
  20.   
  21.     public static void main(String[] args) throws IOException   
  22.   
  23.     {   
  24.   
  25.         HttpClient client = new HttpClient();   
  26.   
  27.         client.getHostConfiguration().setHost("www.imobile.com.cn"80"http");   
  28.   
  29.         HttpMethod method = getPostMethod();//使用POST方式提交数据   
  30.   
  31.         client.executeMethod(method);   
  32.   
  33.        //打印服务器返回的状态   
  34.   
  35.         System.out.println(method.getStatusLine());   
  36.   
  37.         //打印结果页面   
  38.   
  39.         String response =   
  40.   
  41.            new String(method.getResponseBodyAsString().getBytes("8859_1"));   
  42.   
  43.        //打印返回的信息   
  44.   
  45.         System.out.println(response);   
  46.   
  47.         method.releaseConnection();   
  48.   
  49.     }   
  50.   
  51.     /**  
  52.  
  53.      * 使用GET方式提交数据  
  54.  
  55.      * @return  
  56.  
  57.      */  
  58.   
  59.     private static HttpMethod getGetMethod(){   
  60.   
  61.         return new GetMethod("/simcard.php?simcard=1330227");   
  62.   
  63.     }   
  64.   
  65.     /**  
  66.  
  67.      * 使用POST方式提交数据  
  68.  
  69.      * @return  
  70.  
  71.      */  
  72.   
  73.     private static HttpMethod getPostMethod(){   
  74.   
  75.         PostMethod post = new PostMethod("/simcard.php");   
  76.   
  77.         NameValuePair simcard = new NameValuePair("simcard","1330227");   
  78.   
  79.         post.setRequestBody(new NameValuePair[] { simcard});   
  80.   
  81.         return post;   
  82.   
  83.     }   
  84.   
  85. }  



3. 处理页面重定向

详细描述:

状态码  对应HttpServletResponse的常量

301   SC_MOVED_PERMANENTLY  页面已经永久移到另外一个新地址

302   SC_MOVED_TEMPORARILY  页面暂时移动到另外一个新的地址

303   SC_SEE_OTHER  客户端请求的地址必须通过另外的URL来访问

307   SC_TEMPORARY_REDIRECT  同 SC_MOVED_TEMPORARILY


下面的代码片段演示如何处理页面的重定向

Java代码
  1. client.executeMethod(post);   
  2.   
  3. System.out.println(post.getStatusLine().toString());   
  4.   
  5. post.releaseConnection();   
  6.   
  7. //检查是否重定向   
  8.   
  9. int statuscode = post.getStatusCode();   
  10.   
  11. if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||   
  12.   
  13.     (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||   
  14.   
  15.     (statuscode == HttpStatus.SC_SEE_OTHER) ||   
  16.   
  17.     statuscode == HttpStatus.SC_TEMPORARY_REDIRECT))    
  18.   
  19.   
  20.     //读取新的URL地址   
  21.   
  22.     Header header = post.getResponseHeader("location");   
  23.   
  24.     if (header != null)   
  25.     {   
  26.   
  27.         String newuri = header.getValue();   
  28.   
  29.         if ((newuri == null) || (newuri.equals("")))   
  30.   
  31.                    newuri = "/";   
  32.   
  33.   
  34.         GetMethod redirect = new GetMethod(newuri);   
  35.   
  36.         client.executeMethod(redirect);   
  37.   
  38.         System.out.println("Redirect:"+   
  39.                  redirect.getStatusLine().toString());   
  40.   
  41.         redirect.releaseConnection();   
  42.   
  43.     } else  
  44.   
  45.          System.out.println("Invalid redirect");   
  46.   
  47.    }   


4. 模拟输入用户名和口令进行登录


     本小节应该说是HTTP客户端编程中最常碰见的问题,很多网站的内容都只是对注册用户可见的,这种情况下就必须要求使用正确的用户名和口令登录成功后,方可浏览到想要的页面。因为HTTP协议是无状态的,也就是连接的有效期只限于当前请求,请求内容结束后连接就关闭了。在这种情况下为了保存用户的登录信息必须使用到Cookie机制。以JSP/Servlet为例,当浏览器请求一个JSP或者是Servlet的页面时,应用服务器会返回一个参数,名为jsessionid(因不同应用服务器而异),值是一个较长的唯一字符串的Cookie,这个字符串值也就是当前访问该站点的会话标识。浏览器在每访问该站点的其他页面时候都要带上jsessionid这样的Cookie信息,应用服务器根据读取这个会话标识来获取对应的会话信息。

     对于需要用户登录的网站,一般在用户登录成功后会将用户资料保存在服务器的会话中,这样当访问到其他的页面时候,应用服务器根据浏览器送上的Cookie中读取当前请求对应的会话标识以获得对应的会话信息,然后就可以判断用户资料是否存在于会话信息中,如果存在则允许访问页面,否则跳转到登录页面中要求用户输入账号和口令进行登录。这就是一般使用JSP开发网站在处理用户登录的比较通用的方法。
 
     对于HTTP的客户端来讲,如果要访问一个受保护的页面时就必须模拟浏览器所做的工作,首先就是请求登录页面,然后读取Cookie值;再次请求登录页面并加入登录页所需的每个参数;最后就是请求最终所需的页面。当然在除第一次请求外其他的请求都需要附带上 Cookie信息以便服务器能判断当前请求是否已经通过验证。


Java代码
  1. package http.demo;   
  2.   
  3. import org.apache.commons.httpclient.*;   
  4.   
  5. import org.apache.commons.httpclient.cookie.*;   
  6.   
  7. import org.apache.commons.httpclient.methods.*;   
  8.   
  9. /**  
  10.  
  11. * 用来演示登录表单的示例  
  12.  
  13. */  
  14.   
  15. public class FormLoginDemo {   
  16.   
  17.     static final String LOGON_SITE = "localhost";   
  18.   
  19.     static final int    LOGON_PORT = 8080;   
  20.   
  21.       
  22.   
  23.     public static void main(String[] args) throws Exception{   
  24.   
  25.         HttpClient client = new HttpClient();   
  26.   
  27.         client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);   
  28.   
  29.          
  30.   
  31.        //模拟登录页面login.jsp->main.jsp   
  32.   
  33.         PostMethod post = new PostMethod("/main.jsp");   
  34.   
  35.         NameValuePair name = new NameValuePair("name""ld");       
  36.   
  37.         NameValuePair pass = new NameValuePair("password""ld");       
  38.   
  39.         post.setRequestBody(new NameValuePair[]{name,pass});   
  40.   
  41.        int status = client.executeMethod(post);   
  42.   
  43.         System.out.println(post.getResponseBodyAsString());   
  44.   
  45.         post.releaseConnection();   
  46.   
  47.          
  48.   
  49.        //查看cookie信息   
  50.   
  51.         CookieSpec cookiespec = CookiePolicy.getDefaultSpec();   
  52.   
  53.         Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/"false, client.getState().getCookies());   
  54.   
  55.        if (cookies.length == 0) {   
  56.   
  57.            System.out.println("None");      
  58.   
  59.        } else {   
  60.   
  61.            for (int i = 0; i < cookies.length; i++) {   
  62.   
  63.                System.out.println(cookies[i].toString());      
  64.   
  65.            }   
  66.   
  67.        }   
  68.   
  69.        //访问所需的页面main2.jsp   
  70.   
  71.         GetMethod get = new GetMethod("/main2.jsp");   
  72.   
  73.         client.executeMethod(get);   
  74.   
  75.         System.out.println(get.getResponseBodyAsString());   
  76.   
  77.         get.releaseConnection();   
  78.   
  79.     }   
  80.   
  81. }  


5. 提交XML格式参数

提交XML格式的参数很简单,仅仅是一个提交时候的ContentType问题,下面的例子演示从文件文件中读取XML信息并提交给服务器的过程,该过程可以用来测试Web服务。

Java代码
  1. import java.io.File;   
  2.   
  3. import java.io.FileInputStream;   
  4.   
  5. import org.apache.commons.httpclient.HttpClient;   
  6.   
  7. import org.apache.commons.httpclient.methods.EntityEnclosingMethod;   
  8.   
  9. import org.apache.commons.httpclient.methods.PostMethod;   
  10.   
  11. /**  
  12.  
  13. * 用来演示提交XML格式数据的例子  
  14.  
  15. */  
  16.   
  17. public class PostXMLClient {   
  18.   
  19.     public static void main(String[] args) throws Exception {   
  20.   
  21.         File input = new File(“test.xml”);   
  22.   
  23.         PostMethod post = new PostMethod(“http://localhost:8080/httpclient/xml.jsp”);   
  24.   
  25.         // 设置请求的内容直接从文件中读取   
  26.   
  27.         post.setRequestBody(new FileInputStream(input));   
  28.   
  29.           
  30.   
  31.         if (input.length() < Integer.MAX_VALUE)   
  32.   
  33.             post.setRequestContentLength(input.length());   
  34.   
  35.         else            post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);   
  36.   
  37.           
  38.   
  39.         // 指定请求内容的类型   
  40.   
  41.         post.setRequestHeader("Content-type""text/xml; charset=GBK");   
  42.   
  43.           
  44.   
  45.         HttpClient httpclient = new HttpClient();   
  46.   
  47.         int result = httpclient.executeMethod(post);   
  48.   
  49.         System.out.println("Response status code: " + result);   
  50.   
  51.         System.out.println("Response body: ");   
  52.   
  53.         System.out.println(post.getResponseBodyAsString());   
  54.   
  55.         post.releaseConnection();   
  56.   
  57.     }   
  58.   
  59. }  


6. 通过HTTP上传文件

        httpclient使用了单独的一个HttpMethod子类来处理文件的上传,这个类就是MultipartPostMethod,该类已经封装了文件上传的细节,我们要做的仅仅是告诉它我们要上传文件的全路径即可,下面的代码片段演示如何使用这个类。

Java代码
  1. MultipartPostMethod filePost = new MultipartPostMethod(targetURL);   
  2.   
  3. filePost.addParameter("fileName", targetFilePath);   
  4.   
  5. HttpClient client = new HttpClient();   
  6.   
  7. //由于要上传的文件可能比较大,因此在此设置最大的连接超时时间   
  8.   
  9. client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);   
  10.   
  11. int status = client.executeMethod(filePost);  


上面代码中,targetFilePath即为要上传的文件所在的路径。

7. 访问启用认证的页面

     我们经常会碰到这样的页面,当访问它的时候会弹出一个浏览器的对话框要求输入用户名和密码后方可,这种用户认证的方式不同于我们在前面介绍的基于表单的用户身份验证。

    这是HTTP的认证策略,httpclient支持三种认证方式包括: 基本、摘要以及NTLM认证。

    其中基本认证最简单、通用但也最不安全;摘要认证是在HTTP 1.1中加入的认证方式,
而NTLM则是微软公司定义的而不是通用的规范,最新版本的NTLM是比摘要认证还要安全的一种方式。


Java代码
  1. import org.apache.commons.httpclient.HttpClient;   
  2.   
  3. import org.apache.commons.httpclient.UsernamePasswordCredentials;   
  4.   
  5. import org.apache.commons.httpclient.methods.GetMethod;   
  6.   
  7. public class BasicAuthenticationExample {   
  8.   
  9.     public BasicAuthenticationExample() {   
  10.   
  11.     }   
  12.   
  13.     public static void main(String[] args) throws Exception {   
  14.   
  15.         HttpClient client = new HttpClient();   
  16.   
  17.         client.getState().setCredentials(   
  18.   
  19.             "www.verisign.com",   
  20.   
  21.             "realm",   
  22.   
  23.             new UsernamePasswordCredentials("username""password")   
  24.   
  25.         );   
  26.   
  27.         GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");   
  28.   
  29.         get.setDoAuthentication( true );   
  30.   
  31.         int status = client.executeMethod( get );   
  32.   
  33.         System.out.println(status+""+ get.getResponseBodyAsString());   
  34.   
  35.         get.releaseConnection();   
  36.   
  37.     }   
  38.   
  39. }  


8. 多线程模式下使用httpclient
  
    多线程同时访问httpclient,例如同时从一个站点上下载多个文件。对于同一个HttpConnection 同一个时间只能有一个线程访问,为了保证多线程工作环境下不产生冲突,httpclient使用了一个多线程连接管理器类:MultiThreadedHttpConnectionManager,要使用这个类很简单,只需要在构造HttpClient实例的时候传入即可,代码如下:

Java代码
  1. MultiThreadedHttpConnectionManager connectionManager =   
  2.   
  3.    new MultiThreadedHttpConnectionManager();   
  4.   
  5. HttpClient client = new HttpClient(connectionManager);  


以后尽管访问client实例即可。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
用HttpClient来模拟浏览器GET POST
HttpClient登录人人网
HttpClient中使用代理连接
運用Apache HttpClient實作Get與Post動作 - 小嘴冰凉 - ITey...
Apache Commons工具集简介
httpclient 学习测试 实例 示例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服