httpclient4.2实例

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。在Android系统中内置了HttpClient。 

http://hc.apache.org/httpcomponents-client-ga/index.html 

版本:httpclient-4.2.jar
 

1、基本请求 

Java代码  收藏代码

  1. //创建一个客户端  

  2. HttpClient client = new DefaultHttpClient();  

  3.   

  4. //创建一个get方法  

  5. HttpGet get = new HttpGet("http://www.baidu.com");  

  6.   

  7. //执行请求  

  8. HttpResponse res = client.execute(get);  

  9.   

  10. //获取协议版本・・・「HTTP/1.1」  

  11. System.out.println(res.getProtocolVersion());  

  12. //获取返回状态码・・・「200」  

  13. System.out.println(res.getStatusLine().getStatusCode());  

  14. //获取原因短语・・・「OK」  

  15. System.out.println(res.getStatusLine().getReasonPhrase());  

  16. //获取完整的StatusLine・・・「HTTP/1.1 200 OK」  

  17. System.out.println(res.getStatusLine().toString());  

  18.   

  19. //获取返回头部信息  

  20. Header[] headers = res.getAllHeaders();  

  21. for (Header header : headers) {  

  22.     System.out.println(header.getName() + ": " + header.getValue());  

  23. }  

  24.   

  25. //获取返回内容  

  26. if (res.getEntity() != null) {  

  27.     System.out.println(EntityUtils.toString(res.getEntity()));  

  28. }  

  29.   

  30. //关闭流  

  31. EntityUtils.consume(res.getEntity());  

  32.   

  33. //关闭连接  

  34. client.getConnectionManager().shutdown();  



2、操作Cookie 

Java代码  收藏代码

  1. //生成Cookie  

  2. CookieStore cookieStore = new BasicCookieStore();  

  3. BasicClientCookie stdCookie = new BasicClientCookie("name""value");  

  4. stdCookie.setVersion(1);  

  5. stdCookie.setDomain(".baidu.com");  

  6. stdCookie.setPath("/");  

  7. stdCookie.setSecure(true);  

  8. stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1");  

  9. stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".baidu.com");  

  10. cookieStore.addCookie(stdCookie);  

  11.   

  12. DefaultHttpClient client1 = new DefaultHttpClient();  

  13. client1.setCookieStore(cookieStore);  

  14.   

  15. client1.execute(new HttpGet("http://www.baidu.com/"));  

  16.   

  17. //获取Cookie  

  18. DefaultHttpClient client2 = new DefaultHttpClient();  

  19. HttpGet httpget = new HttpGet("http://www.baidu.com/");  

  20.   

  21. HttpResponse res = client2.execute(httpget);  

  22.   

  23. List<Cookie> cookies = client2.getCookieStore().getCookies();  

  24. for (Cookie cookie : cookies) {  

  25.     System.out.println(cookie.getName());  

  26.     System.out.println(cookie.getValue());  

  27. }  

  28.   

  29. EntityUtils.consume(res.getEntity());  



3、设置代理 

Java代码  收藏代码

  1. //通过连接参数设置代理  

  2. DefaultHttpClient client1 = new DefaultHttpClient();  

  3.   

  4. HttpHost proxy1 = new HttpHost("192.168.2.60"8080"HTTP");  

  5. client1.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy1);  

  6.   

  7. HttpGet get1 = new HttpGet("http://www.facebook.com");  

  8. HttpResponse res1 = client1.execute(get1);  

  9. if (res1.getEntity() != null) {  

  10.     System.out.println(EntityUtils.toString(res1.getEntity()));  

  11. }         

  12. EntityUtils.consume(res1.getEntity());  

  13.   

  14. //设置代理认证  

  15. //client1.getCredentialsProvider().setCredentials(  

  16. //        new AuthScope("localhost", 8080),  

  17. //        new UsernamePasswordCredentials("username", "password"));  



4、POST数据 

Java代码  收藏代码

  1. //========UrlEncodedFormEntity  

  2. List<NameValuePair> formparams = new ArrayList<NameValuePair>();  

  3. formparams.add(new BasicNameValuePair("param1""value1"));  

  4. formparams.add(new BasicNameValuePair("param2""value2"));  

  5. UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8");  

  6.   

  7. HttpPost post1 = new HttpPost("http://localhost/post1.do");  

  8. post1.setEntity(entity1);  

  9.   

  10. new DefaultHttpClient().execute(post1);  

  11.   

  12. //========FileEntity  

  13. FileEntity entity2 = new FileEntity(new File("c:\\sample.txt"));  

  14. entity2.setContentEncoding("UTF-8");  

  15.   

  16. HttpPost post2 = new HttpPost("http://localhost/post2.do");  

  17. post2.setEntity(entity2);  

  18.   

  19. new DefaultHttpClient().execute(post2);  

  20.   

  21. //========MultipartEntity  

  22. HttpPost post3 = new HttpPost("http://localhost/post3.do");  

  23. File upfile = new File("C:\\test.jpg");  

  24. MultipartEntity entity3 = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));  

  25. entity3.addPart("file_name",     new StringBody(upfile.getName()));  

  26. entity3.addPart("file_contents"new FileBody(upfile));  

  27. post3.setEntity(entity3);  

  28.   

  29. new DefaultHttpClient().execute(post3);  



5、URI构建 

Java代码  收藏代码

  1. //方法一  

  2. URI uri1 = URIUtils.createURI("http""www.baidu.com", -1"/s",  

  3.         "wd=rensanning&rsv_bp=0&rsv_spt=3&inputT=1766"null);  

  4. HttpGet httpget1 = new HttpGet(uri1);  

  5.   

  6. //http://www.baidu.com/s?wd=rensanning&rsv_bp=0&rsv_spt=3&inputT=1766  

  7. System.out.println(httpget1.getURI());  

  8.   

  9. //方法二  

  10. List<NameValuePair> qparams = new ArrayList<NameValuePair>();  

  11. qparams.add(new BasicNameValuePair("wd""rensanning"));  

  12. qparams.add(new BasicNameValuePair("rsv_bp""0"));  

  13. qparams.add(new BasicNameValuePair("rsv_spt""3"));  

  14. qparams.add(new BasicNameValuePair("inputT""1766"));  

  15.   

  16. URI uri2 = URIUtils.createURI("http""www.baidu.com", -1"/s",  

  17.         URLEncodedUtils.format(qparams, "UTF-8"), null);  

  18. HttpGet httpget2 = new HttpGet(uri2);  

  19.   

  20. //http://www.baidu.com/s?wd=rensanning&rsv_bp=0&rsv_spt=3&inputT=1766  

  21. System.out.println(httpget2.getURI());  



6、使用Scheme 

Java代码  收藏代码

  1. DefaultHttpClient  httpclient = new DefaultHttpClient();  

  2.   

  3. //========将Scheme设置到client中  

  4. SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();  

  5.   

  6. Scheme httpsScheme = new Scheme("https"443, socketFactory);  

  7. httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);  

  8.   

  9. HttpGet httpget = new HttpGet("https://xxx.xxx.xxx");  

  10. HttpResponse res =  httpclient.execute(httpget);  

  11.   

  12. System.out.println(EntityUtils.toString(res.getEntity()));  

  13.   

  14. //========使用证书做SSL连接  

  15. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());  

  16. FileInputStream fis = new FileInputStream("c:\\aa.keystore");  

  17. try {  

  18.     keyStore.load(fis, "password".toCharArray());  

  19. finally {  

  20.     fis.close();  

  21. }  

  22.   

  23. @SuppressWarnings("unused")  

  24. SSLSocketFactory socketFactory2 = new SSLSocketFactory(keyStore);  

  25. //......  



7、认证 

Java代码  收藏代码

  1. //========BASIC认证  

  2. DefaultHttpClient httpclient1 = new DefaultHttpClient();  

  3.   

  4. UsernamePasswordCredentials creds1 = new UsernamePasswordCredentials("userid""password");  

  5. AuthScope auth1 = new AuthScope("localhost"80);  

  6.   

  7. httpclient1.getCredentialsProvider().setCredentials(auth1, creds1);  

  8.   

  9. HttpGet httpget1 = new HttpGet("http://localhost/auth1");  

  10.   

  11. @SuppressWarnings("unused")  

  12. HttpResponse res1 =  httpclient1.execute(httpget1);  

  13.   

  14. //========BASIC认证(HttpContext)  

  15. DefaultHttpClient httpclient2 = new DefaultHttpClient();  

  16.   

  17. UsernamePasswordCredentials creds2 = new UsernamePasswordCredentials("admin""admin");  

  18. AuthScope auth2 = new AuthScope("localhost"80);  

  19.   

  20. httpclient2.getCredentialsProvider().setCredentials(auth2, creds2);  

  21.   

  22. HttpHost targetHost2 = new HttpHost("localhost"80"http");  

  23.   

  24. AuthCache authCache = new BasicAuthCache();  

  25. BasicScheme basicAuth = new BasicScheme();  

  26. authCache.put(targetHost2, basicAuth);  

  27.   

  28. BasicHttpContext localcontext2 = new BasicHttpContext();  

  29. localcontext2.setAttribute(ClientContext.AUTH_CACHE, authCache);  

  30.   

  31. HttpGet httpget2 = new HttpGet("http://localhost/auth2");  

  32.   

  33. @SuppressWarnings("unused")  

  34. HttpResponse res2 =  httpclient2.execute(httpget2, localcontext2);  

  35.   

  36. //========DIGEST认证  

  37. DefaultHttpClient httpclient3 = new DefaultHttpClient();  

  38.   

  39. UsernamePasswordCredentials creds3 = new UsernamePasswordCredentials("admin""admin");  

  40. AuthScope auth3 = new AuthScope("localhost"80);  

  41.   

  42. httpclient3.getCredentialsProvider().setCredentials(auth3, creds3);  

  43.   

  44. HttpHost targetHost3 = new HttpHost("localhost"80"http");  

  45.   

  46. AuthCache authCache3 = new BasicAuthCache();  

  47. DigestScheme digestAuth = new DigestScheme();  

  48. digestAuth.overrideParamter("realm""some realm");  

  49. digestAuth.overrideParamter("nonce""whatever");  

  50. authCache3.put(targetHost3, digestAuth);  

  51.   

  52. BasicHttpContext localcontext3 = new BasicHttpContext();  

  53. localcontext3.setAttribute(ClientContext.AUTH_CACHE, authCache3);  

  54.   

  55. HttpGet httpget3 = new HttpGet("http://localhost/auth3");  

  56.   

  57. @SuppressWarnings("unused")  

  58. HttpResponse res3 =  httpclient2.execute(httpget3, localcontext3);  

  59.   

  60. //========NTLM认证  

  61. DefaultHttpClient httpclient4 = new DefaultHttpClient();  

  62.   

  63. NTCredentials creds4 = new NTCredentials("user""pwd""myworkstation""microsoft.com");  

  64.   

  65. httpclient4.getCredentialsProvider().setCredentials(AuthScope.ANY, creds4);  

  66.   

  67. HttpHost targetHost4 = new HttpHost("hostname"80"http");  

  68.   

  69. HttpContext localcontext4 = new BasicHttpContext();  

  70.   

  71. HttpGet httpget4 = new HttpGet("http://localhost/auth4");  

  72.   

  73. @SuppressWarnings("unused")  

  74. HttpResponse res4 = httpclient3.execute(targetHost4, httpget4, localcontext4);  



8、连接池 

Java代码  收藏代码

  1. SchemeRegistry schemeRegistry = new SchemeRegistry();  

  2. schemeRegistry.register(new Scheme("http"80, PlainSocketFactory.getSocketFactory()));  

  3. schemeRegistry.register(new Scheme("https"443, SSLSocketFactory.getSocketFactory()));  

  4.   

  5. PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);  

  6. //设置连接最大数  

  7. cm.setMaxTotal(200);  

  8. //设置每个Route的连接最大数  

  9. cm.setDefaultMaxPerRoute(20);  

  10. //设置指定域的连接最大数  

  11. HttpHost localhost = new HttpHost("locahost"80);  

  12. cm.setMaxPerRoute(new HttpRoute(localhost), 50);  

  13.   

  14. HttpGet httpget = new HttpGet("http://localhost/pool");  

  15.   

  16. HttpClient client = new DefaultHttpClient(cm);  

  17.   

  18. @SuppressWarnings("unused")  

  19. HttpResponse res = client.execute(httpget);  



你可能感兴趣的:(httpclient4.2实例)