HttpClient

来源:互联网 发布:程序员入职心得体会 编辑:程序博客网 时间:2024/05/01 17:34
1:概述 

HttpClient是HttpComponents(简称为hc)项目其中的一部份,访问地址:http://hc.apache.org/ 


HttpClient是一个代码级的Http客户端工具,可以使用它模拟浏览器向Http服务器发送请求。使用HttpClient还需要HttpCore.后者包括Http请求与Http响应的代码封装。 

 

2:HttpGet 

Java代码  收藏代码
  1. public final static void main(String[] args) throws Exception {  
  2.     HttpClient httpclient = new DefaultHttpClient();  
  3.     try {  
  4.         HttpGet httpget = new HttpGet("http://www.apache.org/");  
  5.         System.out.println("executing request " + httpget.getURI());  
  6.         HttpResponse response = httpclient.execute(httpget);  
  7.         HttpEntity entity = response.getEntity();  
  8.   
  9.         System.out.println("----------------------------------------");  
  10.         System.out.println(response.getStatusLine());  
  11.         if (entity != null) {  
  12.             System.out.println("Response content length: " + entity.getContentLength());  
  13.         }  
  14.         System.out.println("----------------------------------------");  
  15.   
  16.         InputStream inSm = entity.getContent();  
  17.         Scanner inScn = new Scanner(inSm);  
  18.         while (inScn.hasNextLine()) {  
  19.             System.out.println(inScn.nextLine());  
  20.         }  
  21.         // Do not feel like reading the response body  
  22.         // Call abort on the request object  
  23.         httpget.abort();  
  24.     } finally {  
  25.         // When HttpClient instance is no longer needed,  
  26.         // shut down the connection manager to ensure  
  27.         // immediate deallocation of all system resources  
  28.         httpclient.getConnectionManager().shutdown();  
  29.     }  
  30. }  




httpcore:EntityUtils.toString(httpEntity) 

读取response响应内容部分,也可以借助于 httpcore-4.1.2.jar 里面的 
Java代码  收藏代码
  1. String content = EntityUtils.toString(httpEntity);  


具体: 
Java代码  收藏代码
  1. /** 
  2.  * User: liuwentao 
  3.  * Time: 12-1-25 下午1:23 
  4.  */  
  5. public class Demo1 {  
  6.   
  7.     /** 
  8.      * 用 get 方法访问 www.apache.org 并返回内容 
  9.      * 
  10.      * @param args 
  11.      */  
  12.     public static void main(String[] args) {  
  13.         //创建默认的 HttpClient 实例  
  14.         HttpClient httpClient = new DefaultHttpClient();  
  15.         try {  
  16.             //创建 httpUriRequest 实例  
  17.             HttpGet httpGet = new HttpGet("http://www.apache.org/");  
  18.             System.out.println("uri=" + httpGet.getURI());  
  19.   
  20.             //执行 get 请求  
  21.             HttpResponse httpResponse = httpClient.execute(httpGet);  
  22.   
  23.             //获取响应实体  
  24.             HttpEntity httpEntity = httpResponse.getEntity();  
  25.             //打印响应状态  
  26.             System.out.println(httpResponse.getStatusLine());  
  27.             if (httpEntity != null) {  
  28.                 //响应内容的长度  
  29.                 long length = httpEntity.getContentLength();  
  30.                 //响应内容  
  31.                 String content = EntityUtils.toString(httpEntity);  
  32.   
  33.                 System.out.println("Response content length:" + length);  
  34.                 System.out.println("Response content:" + content);  
  35.             }  
  36.   
  37.             //有些教程里没有下面这行  
  38.             httpGet.abort();  
  39.         } catch (Exception e) {  
  40.             e.printStackTrace();  
  41.         } finally {  
  42.             //关闭连接,释放资源  
  43.             httpClient.getConnectionManager().shutdown();  
  44.         }  
  45.     }  
  46. }  


执行结果: 



httpget.setHeader 

1:分析请求包中这六个头信息 

 

2:代码 
Java代码  收藏代码
  1. /** 
  2.  * @param args 
  3.  * @throws IOException 
  4.  */  
  5. public static void main(String[] args) {  
  6.     HttpClient httpClient = new DefaultHttpClient();  
  7.     try {  
  8.         HttpGet httpget = new HttpGet("http://www.iteye.com");  
  9.   
  10.         httpget.setHeader("Accept""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");  
  11.         httpget.setHeader("Accept-Language""zh-cn,zh;q=0.5");  
  12.         httpget.setHeader("User-Agent""Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");  
  13.         httpget.setHeader("Accept-Encoding""gzip, deflate");  
  14.         httpget.setHeader("Accept-Charset""GB2312,utf-8;q=0.7,*;q=0.7");  
  15.         httpget.setHeader("Host""www.iteye.com");  
  16.         httpget.setHeader("Connection""Keep-Alive");  
  17.   
  18.         HttpResponse response = httpClient.execute(httpget);  
  19.         HttpEntity entity = response.getEntity();  
  20.   
  21.         System.out.println("----------------------------------------");  
  22.         System.out.println(response.getStatusLine());  
  23.         if (entity != null) {  
  24.             System.out.println("Response content length: " + entity.getContentLength());  
  25.         }  
  26.         System.out.println("----------------------------------------");  
  27.   
  28.         InputStream inSm = entity.getContent();  
  29.         Scanner inScn = new Scanner(inSm);  
  30.         while (inScn.hasNextLine()) {  
  31.             System.out.println(inScn.nextLine());  
  32.         }  
  33.         // Do not feel like reading the response body  
  34.         // Call abort on the request object  
  35.         httpget.abort();  
  36.     } catch (Exception e) {  
  37.         e.printStackTrace();  
  38.     } finally {  
  39.         // When HttpClient instance is no longer needed,  
  40.         // shut down the connection manager to ensure  
  41.         // immediate deallocation of all system resources  
  42.         httpClient.getConnectionManager().shutdown();  
  43.     }  
  44. }  

3:效果 



以上乱码是由于 
Java代码  收藏代码
  1. httpget.setHeader("Accept-Encoding""gzip, deflate");    

注释掉这行,具体: 
Java代码  收藏代码
  1. /** 
  2.  * User: liuwentao 
  3.  * Time: 12-1-25 下午1:23 
  4.  */  
  5. public class Demo3 {  
  6.   
  7.     /** 
  8.      * 用 get 方法访问 www.baidu.com 并返回内容 
  9.      * 
  10.      * @param args 
  11.      */  
  12.     public static void main(String[] args) {  
  13.         //创建默认的 HttpClient 实例  
  14.         HttpClient httpClient = new DefaultHttpClient();  
  15.   
  16.         try {  
  17.             //创建 httpUriRequest 实例  
  18.             HttpGet httpGet = new HttpGet("http://www.iteye.com");  
  19.   
  20.             httpGet.setHeader("Accept""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");  
  21.             httpGet.setHeader("Accept-Language""zh-cn,zh;q=0.5");  
  22.             httpGet.setHeader("User-Agent""Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");  
  23. //            httpGet.setHeader("Accept-Encoding", "gzip, deflate");  
  24.             httpGet.setHeader("Accept-Charset""GB2312,utf-8;q=0.7,*;q=0.7");  
  25.             httpGet.setHeader("Host""www.iteye.com");  
  26.             httpGet.setHeader("Connection""Keep-Alive");  
  27.             System.out.println("uri=" + httpGet.getURI());  
  28.   
  29.             //执行 get 请求  
  30.             HttpResponse httpResponse = httpClient.execute(httpGet);  
  31.   
  32.             //获取响应实体  
  33.             HttpEntity httpEntity = httpResponse.getEntity();  
  34.             //打印响应状态  
  35.             System.out.println(httpResponse.getStatusLine());  
  36.             if (httpEntity != null) {  
  37.                 //响应内容的长度  
  38.                 long length = httpEntity.getContentLength();  
  39.                 //响应内容  
  40.                 String content = EntityUtils.toString(httpEntity);  
  41.   
  42.                 System.out.println("Response content length:" + length);  
  43.                 System.out.println("Response content:" + content);  
  44.             }  
  45.   
  46.             //有些教程里没有下面这行  
  47.             httpGet.abort();  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         } finally {  
  51.             //关闭连接,释放资源  
  52.             httpClient.getConnectionManager().shutdown();  
  53.         }  
  54.     }  
  55. }  


效果: 


用post方法访问本地应用根据传递参数不同,返回不同结果 

web.xml 
Java代码  收藏代码
  1. <servlet>  
  2.     <servlet-name>Test1Servlet</servlet-name>  
  3.     <servlet-class>demo.servlet.Test1Servlet</servlet-class>  
  4. </servlet>  
  5. <servlet-mapping>  
  6.     <servlet-name>Test1Servlet</servlet-name>  
  7.     <url-pattern>/test1Servlet</url-pattern>  
  8. </servlet-mapping>  


Test1Servlet.java 
Java代码  收藏代码
  1. /** 
  2.  * User: liuwentao 
  3.  * Time: 11-12-25 下午1:08 
  4.  */  
  5. public class Test1Servlet extends HttpServlet {  
  6.     @Override  
  7.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  8.             throws ServletException, IOException {  
  9.         //接收地址栏参数  
  10.         String param1 = request.getParameter("param1");  
  11.         //输出  
  12.         response.setContentType("text/html;charset=UTF-8");  
  13.         PrintWriter out = response.getWriter();  
  14.         out.write("你传递来的参数param1=" + param1);  
  15.         out.close();  
  16.     }  
  17. }  

Demo2.java 
Java代码  收藏代码
  1. /** 
  2.  * User: liuwentao 
  3.  * Time: 12-1-25 下午1:23 
  4.  */  
  5. public class Demo2 {  
  6.   
  7.     /** 
  8.      * 用post方法访问本地应用根据传递参数不同,返回不同结果 
  9.      * 
  10.      * @param args 
  11.      */  
  12.     public static void main(String[] args) {  
  13.         //创建默认的 HttpClient 实例  
  14.         HttpClient httpClient = new DefaultHttpClient();  
  15.   
  16.         HttpPost httpPost = new HttpPost("http://localhost:86/test1Servlet");  
  17.   
  18.         List<NameValuePair> formParams = new ArrayList<NameValuePair>();  
  19.         formParams.add(new BasicNameValuePair("param1""刘文涛"));  
  20.         UrlEncodedFormEntity urlEncodedFormEntity;  
  21.   
  22.         try {  
  23.             urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");  
  24.             httpPost.setEntity(urlEncodedFormEntity);  
  25.             System.out.println("execurting request:" + httpPost.getURI());  
  26.             HttpResponse httpResponse = null;  
  27.             httpResponse = httpClient.execute(httpPost);  
  28.             HttpEntity httpEntity = httpResponse.getEntity();  
  29.             if (httpEntity != null) {  
  30.                 String content = EntityUtils.toString(httpEntity, "UTF-8");  
  31.                 System.out.println("Response content:" + content);  
  32.             }  
  33.         } catch (ClientProtocolException e) {  
  34.             e.printStackTrace();  
  35.         } catch (UnsupportedEncodingException e) {  
  36.             e.printStackTrace();  
  37.         } catch (IOException e) {  
  38.             e.printStackTrace();  
  39.         } finally {  
  40.             //关闭连接,释放资源  
  41.             httpClient.getConnectionManager().shutdown();  
  42.         }  
  43.     }  
  44. }  


结果: 

 
0 0
原创粉丝点击