转账注明出处:http://renjie120.iteye.com/blog/1727933

在工作中要用到android,然后进行网络请求的时候,打算使用httpClient。

总结一下httpClient的一些基本使用。

版本是4.2.2。

使用这个版本的过程中,百度很多,结果都是出现的org.apache.commons.httpclient.这个包名,而不是我这里的org.apache.http.client.HttpClient----------前者版本是 Commons HttpClient 3.x ,不是最新的版本HttpClient 4.×。

官网上面:

Commons HttpClient 3.x codeline is at the end of life. All users of Commons HttpClient 3.x are strongly encouraged to upgrade to HttpClient 4.1.

1.基本的get

  1. public void getUrl(String url, String encoding)
  2. throws ClientProtocolException, IOException {
  3. // 默认的client类。
  4. HttpClient client = new DefaultHttpClient();
  5. // 设置为get取连接的方式.
  6. HttpGet get = new HttpGet(url);
  7. // 得到返回的response.
  8. HttpResponse response = client.execute(get);
  9. // 得到返回的client里面的实体对象信息.
  10. HttpEntity entity = response.getEntity();
  11. if (entity != null) {
  12. System.out.println("内容编码是:" + entity.getContentEncoding());
  13. System.out.println("内容类型是:" + entity.getContentType());
  14. // 得到返回的主体内容.
  15. InputStream instream = entity.getContent();
  16. try {
  17. BufferedReader reader = new BufferedReader(
  18. new InputStreamReader(instream, encoding));
  19. System.out.println(reader.readLine());
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. } finally {
  23. instream.close();
  24. }
  25. }
  26. // 关闭连接.
  27. client.getConnectionManager().shutdown();
  28. }

2.基本的Post

下面的params参数,是在表单里面提交的参数。

  1. public void postUrlWithParams(String url, Map params, String encoding)
  2. throws Exception {
  3. DefaultHttpClient httpclient = new DefaultHttpClient();
  4. try {
  5. HttpPost httpost = new HttpPost(url);
  6. // 添加参数
  7. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  8. if (params != null && params.keySet().size() > 0) {
  9. Iterator iterator = params.entrySet().iterator();
  10. while (iterator.hasNext()) {
  11. Map.Entry entry = (Entry) iterator.next();
  12. nvps.add(new BasicNameValuePair((String) entry.getKey(),
  13. (String) entry.getValue()));
  14. }
  15. }
  16. httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
  17. HttpResponse response = httpclient.execute(httpost);
  18. HttpEntity entity = response.getEntity();
  19. System.out.println("Login form get: " + response.getStatusLine()
  20. + entity.getContent());
  21. dump(entity, encoding);
  22. System.out.println("Post logon cookies:");
  23. List<Cookie> cookies = httpclient.getCookieStore().getCookies();
  24. if (cookies.isEmpty()) {
  25. System.out.println("None");
  26. } else {
  27. for (int i = 0; i < cookies.size(); i++) {
  28. System.out.println("- " + cookies.get(i).toString());
  29. }
  30. }
  31. } finally {
  32. // 关闭请求
  33. httpclient.getConnectionManager().shutdown();
  34. }
  35. }

3。打印页面输出的小代码片段

  1. private static void dump(HttpEntity entity, String encoding)
  2. throws IOException {
  3. BufferedReader br = new BufferedReader(new InputStreamReader(
  4. entity.getContent(), encoding));
  5. System.out.println(br.readLine());
  6. }

4.常见的登录session问题,需求:使用账户,密码登录系统之后,然后再访问页面不出错。

特别注意,下面的httpclient对象要使用一个,而不要在第二次访问的时候,重新new一个。至于如何保存这个第一步经过了验证的 httpclient,有很多种方法实现。单例,系统全局变量(android 下面的Application),ThreadLocal变量等等。

以及下面创建的httpClient要使用ThreadSafeClientConnManager对象!

public String getSessionId(String url, Map params, String encoding,

  1. String url2) throws Exception {
  2. DefaultHttpClient httpclient = new DefaultHttpClient(
  3. new ThreadSafeClientConnManager());
  4. try {
  5. HttpPost httpost = new HttpPost(url);
  6. // 添加参数
  7. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  8. if (params != null && params.keySet().size() > 0) {
  9. Iterator iterator = params.entrySet().iterator();
  10. while (iterator.hasNext()) {
  11. Map.Entry entry = (Entry) iterator.next();
  12. nvps.add(new BasicNameValuePair((String) entry.getKey(),
  13. (String) entry.getValue()));
  14. }
  15. }
  16. // 设置请求的编码格式
  17. httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
  18. // 登录一遍
  19. httpclient.execute(httpost);
  20. // 然后再第二次请求普通的url即可。
  21. httpost = new HttpPost(url2);
  22. BasicResponseHandler responseHandler = new BasicResponseHandler();
  23. System.out.println(httpclient.execute(httpost, responseHandler));
  24. } finally {
  25. // 关闭请求
  26. httpclient.getConnectionManager().shutdown();
  27. }
  28. return "";
  29. }

5.下载文件,例如mp3等等。

  1. //第一个参数,网络连接;第二个参数,保存到本地文件的地址
  2. public void getFile(String url, String fileName) {
  3. HttpClient httpClient = new DefaultHttpClient();
  4. HttpGet get = new HttpGet(url);
  5. try {
  6. ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
  7. public byte[] handleResponse(HttpResponse response)
  8. throws ClientProtocolException, IOException {
  9. HttpEntity entity = response.getEntity();
  10. if (entity != null) {
  11. return EntityUtils.toByteArray(entity);
  12. } else {
  13. return null;
  14. }
  15. }
  16. };
  17. byte[] charts = httpClient.execute(get, handler);
  18. FileOutputStream out = new FileOutputStream(fileName);
  19. out.write(charts);
  20. out.close();
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. } finally {
  24. httpClient.getConnectionManager().shutdown();
  25. }
  26. }

6.创建一个多线程环境下面可用的httpClient

(原文:http://blog.csdn.net/jiaoshi0531/article/details/6459468

  1. HttpParams params = new BasicHttpParams();
  2. //设置允许链接的做多链接数目
  3. ConnManagerParams.setMaxTotalConnections(params, 200);
  4. //设置超时时间.
  5. ConnManagerParams.setTimeout(params, 10000);
  6. //设置每个路由的最多链接数量是20
  7. ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
  8. //设置到指定主机的路由的最多数量是50
  9. HttpHost localhost = new HttpHost("127.0.0.1",80);
  10. connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50);
  11. ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
  12. //设置链接使用的版本
  13. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  14. //设置链接使用的内容的编码
  15. HttpProtocolParams.setContentCharset(params,
  16. HTTP.DEFAULT_CONTENT_CHARSET);
  17. //是否希望可以继续使用.
  18. HttpProtocolParams.setUseExpectContinue(params, true);
  19. SchemeRegistry schemeRegistry = new SchemeRegistry();
  20. schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  21. schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  22. ClientConnectionManager cm = new ThreadSafeClientConnManager(params,schemeRegistry);
  23. httpClient = new DefaultHttpClient(cm, params);

7.实用的一个对象,http上下文,可以从这个对象里面取到一次请求相关的信息,例如request,response,代理主机等。

  1. public static void getUrl(String url, String encoding)
  2. throws ClientProtocolException, IOException {
  3. // 设置为get取连接的方式.
  4. HttpGet get = new HttpGet(url);
  5. HttpContext localContext = new BasicHttpContext();
  6. // 得到返回的response.第二个参数,是上下文,很好的一个参数!
  7. httpclient.execute(get, localContext);
  8. // 从上下文中得到HttpConnection对象
  9. HttpConnection con = (HttpConnection) localContext
  10. .getAttribute(ExecutionContext.HTTP_CONNECTION);
  11. System.out.println("socket超时时间:" + con.getSocketTimeout());
  12. // 从上下文中得到HttpHost对象
  13. HttpHost target = (HttpHost) localContext
  14. .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  15. System.out.println("最终请求的目标:" + target.getHostName() + ":"
  16. + target.getPort());
  17. // 从上下文中得到代理相关信息.
  18. HttpHost proxy = (HttpHost) localContext
  19. .getAttribute(ExecutionContext.HTTP_PROXY_HOST);
  20. if (proxy != null)
  21. System.out.println("代理主机的目标:" + proxy.getHostName() + ":"
  22. + proxy.getPort());
  23. System.out.println("是否发送完毕:"
  24. + localContext.getAttribute(ExecutionContext.HTTP_REQ_SENT));
  25. // 从上下文中得到HttpRequest对象
  26. HttpRequest request = (HttpRequest) localContext
  27. .getAttribute(ExecutionContext.HTTP_REQUEST);
  28. System.out.println("请求的版本:" + request.getProtocolVersion());
  29. Header[] headers = request.getAllHeaders();
  30. System.out.println("请求的头信息: ");
  31. for (Header h : headers) {
  32. System.out.println(h.getName() + "--" + h.getValue());
  33. }
  34. System.out.println("请求的链接:" + request.getRequestLine().getUri());
  35. // 从上下文中得到HttpResponse对象
  36. HttpResponse response = (HttpResponse) localContext
  37. .getAttribute(ExecutionContext.HTTP_RESPONSE);
  38. HttpEntity entity = response.getEntity();
  39. if (entity != null) {
  40. System.out.println("返回结果内容编码是:" + entity.getContentEncoding());
  41. System.out.println("返回结果内容类型是:" + entity.getContentType());
  42. dump(entity, encoding);
  43. }
  44. }

输出结果大致如下:

  1. socket超时时间:0
  2. 最终请求的目标:money.finance.sina.com.cn:-1
  3. 是否发送完毕:true
  4. 请求的版本:HTTP/1.1
  5. 请求的头信息:
  6. Host--money.finance.sina.com.cn
  7. Connection--Keep-Alive
  8. User-Agent--Apache-HttpClient/4.2.2 (java 1.5)
  9. 请求的链接:/corp/go.php/vFD_BalanceSheet/stockid/600031/ctrl/part/displaytype/4.phtml
  10. 返回结果内容编码是:null
  11. 返回结果内容类型是:Content-Type: text/html

8.设置代理

  1. //String  hostIp代理主机ip,int port  代理端口
  2. tpHost proxy = new HttpHost(hostIp, port);
  3. // 设置代理主机.
  4. tpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
  5. proxy);

9.设置保持链接时间

  1. //在服务端设置一个保持持久连接的特性.
  2. //HTTP服务器配置了会取消在一定时间内没有活动的链接,以节省系统的持久性链接资源.
  3. httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
  4. public long getKeepAliveDuration(HttpResponse response,
  5. HttpContext context) {
  6. HeaderElementIterator it = new BasicHeaderElementIterator(
  7. response.headerIterator(HTTP.CONN_KEEP_ALIVE));
  8. while (it.hasNext()) {
  9. HeaderElement he = it.nextElement();
  10. String param = he.getName();
  11. String value = he.getValue();
  12. if (value != null && param.equalsIgnoreCase("timeout")) {
  13. try {
  14. return Long.parseLong(value) * 1000;
  15. } catch (Exception e) {
  16. }
  17. }
  18. }
  19. HttpHost target = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  20. if("www.baidu.com".equalsIgnoreCase(target.getHostName())){
  21. return 5*1000;
  22. }
  23. else
  24. return 30*1000;
  25. }
  26. });

转账注明出处:http://renjie120.iteye.com/blog/1727933

java应用集锦9:httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件的更多相关文章

  1. crawler_java应用集锦9:httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件_设置代理

    在工作中要用到android,然后进行网络请求的时候,打算使用httpClient. 总结一下httpClient的一些基本使用. 版本是4.2.2. 使用这个版本的过程中,百度很多,结果都是出现的o ...

  2. java 网络编程基础 InetAddress类;URLDecoder和URLEncoder;URL和URLConnection;多线程下载文件示例

    什么是IPV4,什么是IPV6: IPv4使用32个二进制位在网络上创建单个唯一地址.IPv4地址由四个数字表示,用点分隔.每个数字都是十进制(以10为基底)表示的八位二进制(以2为基底)数字,例如: ...

  3. 通过Java WebService接口从服务端下载文件

    一. 前言 本文讲述如何通过webservice接口,从服务端下载文件.报告到客户端.适用于跨系统间的文件交互,传输文件不大的情况(控制在几百M以内).对于这种情况搭建一个FTP环境,增加了系统部署的 ...

  4. Java知识集锦

    Java知识集锦 一.Java程序基础 1.1 开发和运行环境 1.2 Java语言概述 二.Java语法基础 2.1 基础类型和语法 2.2 对象和类型 2.3 包和访问控制 三.数据类型及类型转换 ...

  5. 使用HttpURLConnection下载文件时出现 java.io.FileNotFoundException彻底解决办法

    使用HttpURLConnection下载文件时经常会出现 java.io.FileNotFoundException文件找不到异常,下面介绍下解决办法 首先设置tomcat对get数据的编码:con ...

  6. 多线程爬虫Java调用wget下载文件,独立线程读取输出缓冲区

    写了个抓取appstore的,要抓取大量的app,本来是用httpclient,但是效果不理想,于是直接调用wget下载,但是由于标准输出.错误输出的原因会导致卡住,另外wget也会莫名的卡住. 所以 ...

  7. Java Sftp上传下载文件

    需要使用jar包  jsch-0.1.50.jar sftp上传下载实现类 package com.bstek.transit.sftp; import java.io.File; import ja ...

  8. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

  9. JAVA之旅(三十三)——TCP传输,互相(伤害)传输,复制文件,上传图片,多并发上传,多并发登录

    JAVA之旅(三十三)--TCP传输,互相(伤害)传输,复制文件,上传图片,多并发上传,多并发登录 我们继续网络编程 一.TCP 说完UDP,我们就来说下我们应该重点掌握的TCP了 TCP传输 Soc ...

随机推荐

  1. Choerodon 的微服务之路(二):Choerodon 的微服务网关

    链接地址:https://my.oschina.net/choerodon/blog/2254030

  2. CCS3的过渡、变换、动画以及响应式布局、弹性布局

    CSS3 过渡 .变换.动画 在没有CSS3之前,如果页面上需要一些动画效果,要么你自己编写 JavaScript,要么使用 JavaScript 框架(如 jQuery)来提高效率. 但是CSS3出 ...

  3. [原创]Eclipse 安卓开发几个异常的处理办法

    一.代码没有问题,就是报错,重启一下就会好.可以先clean再build; 二.R.Java丢失 网上讲了若干方法,有用android toos的,有clean再build的,我的解决办法是勾选bui ...

  4. 以shareExtension为例学习iOS扩展开发

    整体介绍 phone Extension 用法基础详解 share Extension 用法基础详解 demo链接   密码: i72z

  5. PowerDesigner 逆向工程Non SQL Error : Could not load class com.mysql.jdbc.Driver

    建立与数据库的连接. 在菜单条上,有一个Database的选择项: 选择connect…后弹出设置对话框: 在Data source里选择第三个单选按钮,即Connection profile:后,点 ...

  6. node linux服务器部署 centos

      1下载 wget https://nodejs.org/dist/v6.9.5/node-v6.9.5-linux-x64.tar.xz  2解压 tar xvf node-v6.9.5-linu ...

  7. PIC EEPROM问题

    1.通过export出来的Hex烧录,EEPROM内容会根据Hex中关于EEPROM的定义而改变. 2.通过编译源文件烧录,如果没有勾选Preserve EEPROM on program则EEPRO ...

  8. 函数GROUP_CONCAT

    这不得不说是mysql中一个特别好用的函数,之前生写这种确实好麻烦..感谢mysql有了这么好的函数..嘿嘿 举个例子吧. s_student 表 stuinfo表 sql如下: ok,简单粗暴,就这 ...

  9. CorelDRAW 2019新品发布,行业大咖就差你了

    近日,由苏州思杰马克丁软件公司独家代理的CorelDRAW 2019将在苏州开启一场设计上的饕餮盛宴,您报名了么? 不管您是专业的设计师还是热爱设计的狂热粉丝,都将有机会参与到我们的活动中,为了这场盛 ...

  10. switch 语句来选择要执行的多个代码块之一。

    switch(n) { case 1: 执行代码块 1 break; case 2: 执行代码块 2 break; default: n 与 case 1 和 case 2 不同时执行的代码 }