jar包

HttpClient 4.x版本

简要介绍

HttpComponents 包括 HttpCore包和HttpClient包

HttpClient:Http的执行http请求

DefaultHttpClient:httpClient默认实现

HttpGet、HttpPost:Get、Post方法执行类

HttpResponse:执行返回的Response,含http的header和执行结果实体Entity

HttpEntity:Http返回结果实体,不含Header内容

HttpParam:连接参数,配合连接池使用

PoolingClientConnectionManager:连接池

基础Get方法

  1. // 默认的client类。
  2. HttpClient client = new DefaultHttpClient();
  3. // 设置为get取连接的方式.
  4. HttpGet get = new HttpGet(url);
  5. // 得到返回的response.
  6. HttpResponse response = client.execute(get);
  7. // 得到返回的client里面的实体对象信息.
  8. HttpEntity entity = response.getEntity();
  9. if (entity != null) {
  10. System.out.println( entity.getContentEncoding());
  11. System.out.println( entity.getContentType());
  12. // 得到返回的主体内容.
  13. InputStream instream = entity.getContent();
  14. BufferedReader reader = new BufferedReader(new InputStreamReader(instream, encoding));
  15. System.out.println(reader.readLine());
  16. // EntityUtils 处理HttpEntity的工具类
  17. // System.out.println(EntityUtils.toString(entity));
  18. }
  19. // 关闭连接.
  20. client.getConnectionManager().shutdown();

基础Post方法

  1. DefaultHttpClient httpclient = new DefaultHttpClient();
  2. HttpPost httpost = new HttpPost(url);
  3. // 添加参数
  4. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  5. formparams.add(new BasicNameValuePair("p", "1"));
  6. formparams.add(new BasicNameValuePair("t", "2"));
  7. formparams.add(new BasicNameValuePair("e", "3"));
  8. UrlEncodedFormEntity urlEntity =  new UrlEncodedFormEntity(formparams, "UTF-8");
  9. httpost.setEntity(urlEntity);
  10. HttpResponse response = httpclient.execute(httpost);
  11. HttpEntity entity = response.getEntity();
  12. System.out.println("Login form get: " + response.getStatusLine() + entity.getContent());
  13. //  dump(entity, encoding);
  14. System.out.println("Post logon cookies:");
  15. List<Cookie> cookies = httpclient.getCookieStore().getCookies();
  16. for (int i = 0; i < cookies.size(); i++) {
  17. System.out.println("- " + cookies.get(i).toString());
  18. }
  19. // 关闭请求
  20. httpclient.getConnectionManager().shutdown();

保留Session,保留用户+密码状态

Demo1,只支持单线程

  1. DefaultHttpClient httpclient = new DefaultHttpClient(
  2. new ThreadSafeClientConnManager());
  3. HttpPost httpost = new HttpPost(url);
  4. // 添加参数
  5. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  6. formparams.add(new BasicNameValuePair("p", "1"));
  7. formparams.add(new BasicNameValuePair("t", "2"));
  8. formparams.add(new BasicNameValuePair("e", "3"));
  9. // 设置请求的编码格式
  10. httpost.setEntity(new UrlEncodedFormEntity(formparams, Consts.UTF_8));
  11. // 登录一遍
  12. httpclient.execute(httpost);
  13. // 然后再第二次请求普通的url即可。
  14. httpost = new HttpPost(url2);
  15. BasicResponseHandler responseHandler = new BasicResponseHandler();
  16. System.out.println(httpclient.execute(httpost, responseHandler));
  17. httpclient.getConnectionManager().shutdown();
  18. return "";

Demo2:第二次请求带上第一次请求的Cookie

用于在用户+密码等候后,后续根据第一次请求的URL获取的Cookie,把这些Cookie添加到第二次请求的Cookie中

  1. DefaultHttpClient httpclient = new DefaultHttpClient();
  2. HttpPost httpost = new HttpPost(url);
  3. // 添加参数
  4. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  5. formparams.add(new BasicNameValuePair("uname", name));
  6. formparams.add(new BasicNameValuePair("pass", "e0c10f451217b93f76c2654b2b729b85"));
  7. formparams.add(new BasicNameValuePair("auto_login","0"));
  8. formparams.add(new BasicNameValuePair("a","1"));
  9. formparams.add(new BasicNameValuePair("backurl","1"));
  10. UrlEncodedFormEntity urlEntity =  new UrlEncodedFormEntity(formparams, "UTF-8");
  11. httpost.setEntity(urlEntity);
  12. HttpContext localContext = new BasicHttpContext();
  13. HttpResponse response = httpclient.execute(httpost,localContext);
  14. HttpEntity entity = response.getEntity();
  15. // 打印获取值
  16. System.out.println(Arrays.toString(response.getAllHeaders()));
  17. System.out.println(EntityUtils.toString(entity));
  18. // 第二次请求,使用上一次请求的Cookie
  19. DefaultHttpClient httpclient2 = new DefaultHttpClient();
  20. HttpPost httpost2 = new HttpPost("http://my.ifeng.com/?_c=index&_a=my");
  21. // 获取上一次请求的Cookie
  22. CookieStore cookieStore2 = httpclient2.getCookieStore();
  23. // 下一次的Cookie的值,将使用上一次请求
  24. CookieStore cookieStore = httpclient.getCookieStore();
  25. List<Cookie> list = cookieStore.getCookies();
  26. for(Cookie o : list){
  27. System.out.println(o.getName() + " = " + o.getValue() + " 12");;
  28. cookieStore2.addCookie(o);
  29. }
  30. HttpResponse response2 = httpclient2.execute(httpost2);
  31. HttpEntity entity2 = response2.getEntity();
  32. System.out.println(Arrays.toString(response2.getAllHeaders()));
  33. System.out.println(EntityUtils.toString(entity2));

获取访问上下文

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

连接池和代理:

每次使用最后一句new DefaultHttpClient(cm, httpParams);获取新的HttpClient

里面还有一条如何设置代理

  1. // HttpParams
  2. HttpParams httpParams  = new BasicHttpParams();
  3. // HttpConnectionParams 设置连接参数
  4. // 设置连接超时时间
  5. HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
  6. // 设置读取超时时间
  7. HttpConnectionParams.setSoTimeout(httpParams, 60000);
  8. SchemeRegistry schemeRegistry = new SchemeRegistry();
  9. schemeRegistry.register(
  10. new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
  11. //      schemeRegistry.register(
  12. //               new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
  13. PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
  14. // 设置最大连接数
  15. cm.setMaxTotal(200);
  16. // 设置每个路由默认最大连接数
  17. cm.setDefaultMaxPerRoute(20);
  18. //      // 设置代理和代理最大路由
  19. //      HttpHost localhost = new HttpHost("locahost", 80);
  20. //      cm.setMaxPerRoute(new HttpRoute(localhost), 50);
  21. // 设置代理,
  22. HttpHost proxy = new HttpHost("10.36.24.3", 60001);
  23. httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY,  proxy);
  24. HttpClient httpClient = new DefaultHttpClient(cm, httpParams);

自动重连

如果某次请求请求失败,可以自动重连

  1. DefaultHttpClient httpClient = new DefaultHttpClient();
  2. // 可以自动重连
  3. HttpRequestRetryHandler requestRetryHandler2 = new HttpRequestRetryHandler() {
  4. // 自定义的恢复策略
  5. public synchronized boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
  6. // 设置恢复策略,在发生异常时候将自动重试3次
  7. if (executionCount > 3) {
  8. // 超过最大次数则不需要重试
  9. return false;
  10. }
  11. if (exception instanceof NoHttpResponseException) {
  12. // 服务停掉则重新尝试连接
  13. return true;
  14. }
  15. if (exception instanceof SSLHandshakeException) {
  16. // SSL异常不需要重试
  17. return false;
  18. }
  19. HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
  20. boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
  21. if (!idempotent) {
  22. // 请求内容相同则重试
  23. return true;
  24. }
  25. return false;
  26. }
  27. };
  28. httpClient.setHttpRequestRetryHandler(requestRetryHandler2);

使用自定义ResponseHandler处理返回的请求

  1. HttpClient httpClient = new DefaultHttpClient();
  2. HttpGet get = new HttpGet(url);
  3. // 定义一个类处理URL返回的结果
  4. ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
  5. public byte[] handleResponse(HttpResponse response)
  6. throws ClientProtocolException, IOException {
  7. HttpEntity entity = response.getEntity();
  8. if (entity != null) {
  9. return EntityUtils.toByteArray(entity);
  10. } else {
  11. return null;
  12. }
  13. }
  14. };
  15. // 不同于 httpClient.execute(request),返回值是HttpResponse;返回值右ResponseHandler决定
  16. byte[] charts = httpClient.execute(get, handler);
  17. FileOutputStream out = new FileOutputStream(fileName);
  18. out.write(charts);
  19. out.close();
  20. httpClient.getConnectionManager().shutdown();

参考文献

HttpClient学习系列 -- 学习总结的更多相关文章

  1. Identity Server4学习系列四之用户名密码获得访问令牌

    1.简介 Identity Server4支持用户名密码模式,允许调用客户端使用用户名密码来获得访问Api资源(遵循Auth 2.0协议)的Access Token,MS可能考虑兼容老的系统,实现了这 ...

  2. Identity Server4学习系列三

    1.简介 在Identity Server4学习系列一和Identity Server4学习系列二之令牌(Token)的概念的基础上,了解了Identity Server4的由来,以及令牌的相关知识, ...

  3. SpringCloud学习系列之七 ----- Zuul路由网关的过滤器和异常处理

    前言 在上篇中介绍了SpringCloud Zuul路由网关的基本使用版本,本篇则介绍基于SpringCloud(基于SpringBoot2.x,.SpringCloud Finchley版)中的路由 ...

  4. 分布式学习系列【dubbo入门实践】

    分布式学习系列[dubbo入门实践] dubbo架构 组成部分:provider,consumer,registry,monitor: provider,consumer注册,订阅类似于消息队列的注册 ...

  5. Entity Framework Code First学习系列目录

    Entity Framework Code First学习系列说明:开发环境为Visual Studio 2010 + Entity Framework 5.0+MS SQL Server 2012, ...

  6. WCF学习系列汇总

    最近在学习WCF,打算把一整个系列的文章都”写“出来,包括理论和实践,这里的“写”是翻译,是国外的大牛写好的,我只是搬运工外加翻译.翻译的不好,大家请指正,谢谢了.如果觉得不错的话,也可以给我点赞,这 ...

  7. EF(Entity Framework)系统学习系列

    好久没写博客了,继续开启霸屏模式,好了,废话不多说,这次准备重新系统学一下EF,一个偶然的机会找到了一个学习EF的网站(http://www.entityframeworktutorial.net/) ...

  8. MVC学习系列4--@helper辅助方法和用户自定义HTML方法

    在HTML Helper,帮助类的帮助下,我们可以动态的创建HTML控件.HTML帮助类是在视图中,用来呈现HTML内容的.HTML帮助类是一个方法,它返回的是string类型的值. HTML帮助类, ...

  9. YYKit学习系列 ---- 开篇

    准备花半年时间系统学习YYKit,  学习过程会放入"YYKit学习系列"这个分类, 喜欢YYKit的可以随时留意我的文章, 一起学习!!!

随机推荐

  1. openssl https证书

    今天摸索了下 HTTPS 的证书生成,以及它在 Nginx 上的部署.由于博客托管在 github 上,没办法部署证书,先记录下,后续有需要方便快捷操作.本文的阐述不一定完善,但是可以让一个初学者了解 ...

  2. win10 + vs2017 + vcpkg —— VC++ 打包工具

    vcpkg 是微软 C++ 团队开发的在 Windows 上运行的 C/C++ 项目包管理工具,可以帮助您在 Windows 平台上获取 C 和 C++ 库. vcpkg 自身也是使用 C++ 开发的 ...

  3. Android线程间异步通信机制源码分析

    本文首先从整体架构分析了Android整个线程间消息传递机制,然后从源码角度介绍了各个组件的作用和完成的任务.文中并未对基础概念进行介绍,关于threadLacal和垃圾回收等等机制请自行研究. 基础 ...

  4. wppay免登录付费查看隐藏内容/付费资源下载

    WPPAY是一款模板兔开发的免登录的付费查看内容/付费下载资源WordPress插件,WPPAY不需要用户注册登录即可支付查看隐藏内容,把整个流程做到极简.发布文章时要隐藏的内容可以利用短代码: [w ...

  5. Django学习案例一(blog):一. 创建project、app

    1.创建project 方法1:使用命令行创建项目.在E盘cmd执行如下命令: django-admin.py startproject myblog 方法2:使用pycharm创建项目.放置位置为D ...

  6. PostgreSQL的HA解决方案-2负载均衡(load balance)

    一.部署说明 1.1 实施环境 本文档实验环境如下: PGSQL主机: 192.168.1.45 PGSQL备机: 192.168.1.50 软件和系统版本 Pgsql 版本: pgsql 9.2.4 ...

  7. 软件开发的MVC构架

    MVC:IDE开发环境开发时,无意中使用的软件结构. 转自于wikipedia:http://zh.wikipedia.org/wiki/MVC 软件的层次划分:框架--组件(设计模式)--算法与数据 ...

  8. 基于SLIC分割的特征点检测

    一:pipeLIne (1):基于模型的pose估计综述: 对于一个3D模型,可以投影到平面,得到不同的位姿,而pose识别是利用所见的2.5D图像,来估计模型,并同时识别出位姿. 3D模型投影时注意 ...

  9. 我的C++笔记(类与对象)

    /* * Main.cpp * * Created on: 2015-7-24 * Author: feiruo */ /* * 类与对象: * * 1.抽象: * 面向对象方法中的抽象,是指对具体问 ...

  10. 一个单元格占两行三列的HTML代码为

    主要是这两个属性: colspan 单元格占多少列 rowspan 单元格占多少行 <table width="200" border="1">&l ...