HttpClient学习系列 -- 学习总结
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方法
- // 默认的client类。
- HttpClient client = new DefaultHttpClient();
- // 设置为get取连接的方式.
- HttpGet get = new HttpGet(url);
- // 得到返回的response.
- HttpResponse response = client.execute(get);
- // 得到返回的client里面的实体对象信息.
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println( entity.getContentEncoding());
- System.out.println( entity.getContentType());
- // 得到返回的主体内容.
- InputStream instream = entity.getContent();
- BufferedReader reader = new BufferedReader(new InputStreamReader(instream, encoding));
- System.out.println(reader.readLine());
- // EntityUtils 处理HttpEntity的工具类
- // System.out.println(EntityUtils.toString(entity));
- }
- // 关闭连接.
- client.getConnectionManager().shutdown();
基础Post方法
- DefaultHttpClient httpclient = new DefaultHttpClient();
- HttpPost httpost = new HttpPost(url);
- // 添加参数
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- formparams.add(new BasicNameValuePair("p", "1"));
- formparams.add(new BasicNameValuePair("t", "2"));
- formparams.add(new BasicNameValuePair("e", "3"));
- UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httpost.setEntity(urlEntity);
- HttpResponse response = httpclient.execute(httpost);
- HttpEntity entity = response.getEntity();
- System.out.println("Login form get: " + response.getStatusLine() + entity.getContent());
- // dump(entity, encoding);
- System.out.println("Post logon cookies:");
- List<Cookie> cookies = httpclient.getCookieStore().getCookies();
- for (int i = 0; i < cookies.size(); i++) {
- System.out.println("- " + cookies.get(i).toString());
- }
- // 关闭请求
- httpclient.getConnectionManager().shutdown();
保留Session,保留用户+密码状态
Demo1,只支持单线程
- DefaultHttpClient httpclient = new DefaultHttpClient(
- new ThreadSafeClientConnManager());
- HttpPost httpost = new HttpPost(url);
- // 添加参数
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- formparams.add(new BasicNameValuePair("p", "1"));
- formparams.add(new BasicNameValuePair("t", "2"));
- formparams.add(new BasicNameValuePair("e", "3"));
- // 设置请求的编码格式
- httpost.setEntity(new UrlEncodedFormEntity(formparams, Consts.UTF_8));
- // 登录一遍
- httpclient.execute(httpost);
- // 然后再第二次请求普通的url即可。
- httpost = new HttpPost(url2);
- BasicResponseHandler responseHandler = new BasicResponseHandler();
- System.out.println(httpclient.execute(httpost, responseHandler));
- httpclient.getConnectionManager().shutdown();
- return "";
Demo2:第二次请求带上第一次请求的Cookie
用于在用户+密码等候后,后续根据第一次请求的URL获取的Cookie,把这些Cookie添加到第二次请求的Cookie中
- DefaultHttpClient httpclient = new DefaultHttpClient();
- HttpPost httpost = new HttpPost(url);
- // 添加参数
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- formparams.add(new BasicNameValuePair("uname", name));
- formparams.add(new BasicNameValuePair("pass", "e0c10f451217b93f76c2654b2b729b85"));
- formparams.add(new BasicNameValuePair("auto_login","0"));
- formparams.add(new BasicNameValuePair("a","1"));
- formparams.add(new BasicNameValuePair("backurl","1"));
- UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httpost.setEntity(urlEntity);
- HttpContext localContext = new BasicHttpContext();
- HttpResponse response = httpclient.execute(httpost,localContext);
- HttpEntity entity = response.getEntity();
- // 打印获取值
- System.out.println(Arrays.toString(response.getAllHeaders()));
- System.out.println(EntityUtils.toString(entity));
- // 第二次请求,使用上一次请求的Cookie
- DefaultHttpClient httpclient2 = new DefaultHttpClient();
- HttpPost httpost2 = new HttpPost("http://my.ifeng.com/?_c=index&_a=my");
- // 获取上一次请求的Cookie
- CookieStore cookieStore2 = httpclient2.getCookieStore();
- // 下一次的Cookie的值,将使用上一次请求
- CookieStore cookieStore = httpclient.getCookieStore();
- List<Cookie> list = cookieStore.getCookies();
- for(Cookie o : list){
- System.out.println(o.getName() + " = " + o.getValue() + " 12");;
- cookieStore2.addCookie(o);
- }
- HttpResponse response2 = httpclient2.execute(httpost2);
- HttpEntity entity2 = response2.getEntity();
- System.out.println(Arrays.toString(response2.getAllHeaders()));
- System.out.println(EntityUtils.toString(entity2));
获取访问上下文:
- HttpClient httpclient = new DefaultHttpClient();
- // 设置为get取连接的方式.
- HttpGet get = new HttpGet(url);
- HttpContext localContext = new BasicHttpContext();
- // 得到返回的response.第二个参数,是上下文,很好的一个参数!
- httpclient.execute(get, localContext);
- // 从上下文中得到HttpConnection对象
- HttpConnection con = (HttpConnection) localContext
- .getAttribute(ExecutionContext.HTTP_CONNECTION);
- System.out.println("socket超时时间:" + con.getSocketTimeout());
- // 从上下文中得到HttpHost对象
- HttpHost target = (HttpHost) localContext
- .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
- System.out.println("最终请求的目标:" + target.getHostName() + ":"
- + target.getPort());
- // 从上下文中得到代理相关信息.
- HttpHost proxy = (HttpHost) localContext
- .getAttribute(ExecutionContext.HTTP_PROXY_HOST);
- if (proxy != null)
- System.out.println("代理主机的目标:" + proxy.getHostName() + ":"
- + proxy.getPort());
- System.out.println("是否发送完毕:"
- + localContext.getAttribute(ExecutionContext.HTTP_REQ_SENT));
- // 从上下文中得到HttpRequest对象
- HttpRequest request = (HttpRequest) localContext
- .getAttribute(ExecutionContext.HTTP_REQUEST);
- System.out.println("请求的版本:" + request.getProtocolVersion());
- Header[] headers = request.getAllHeaders();
- System.out.println("请求的头信息: ");
- for (Header h : headers) {
- System.out.println(h.getName() + "--" + h.getValue());
- }
- System.out.println("请求的链接:" + request.getRequestLine().getUri());
- // 从上下文中得到HttpResponse对象
- HttpResponse response = (HttpResponse) localContext
- .getAttribute(ExecutionContext.HTTP_RESPONSE);
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println("返回结果内容编码是:" + entity.getContentEncoding());
- System.out.println("返回结果内容类型是:" + entity.getContentType());
- }
连接池和代理:
每次使用最后一句new DefaultHttpClient(cm, httpParams);获取新的HttpClient
里面还有一条如何设置代理
- // HttpParams
- HttpParams httpParams = new BasicHttpParams();
- // HttpConnectionParams 设置连接参数
- // 设置连接超时时间
- HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
- // 设置读取超时时间
- HttpConnectionParams.setSoTimeout(httpParams, 60000);
- SchemeRegistry schemeRegistry = new SchemeRegistry();
- schemeRegistry.register(
- new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
- // schemeRegistry.register(
- // new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
- PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
- // 设置最大连接数
- cm.setMaxTotal(200);
- // 设置每个路由默认最大连接数
- cm.setDefaultMaxPerRoute(20);
- // // 设置代理和代理最大路由
- // HttpHost localhost = new HttpHost("locahost", 80);
- // cm.setMaxPerRoute(new HttpRoute(localhost), 50);
- // 设置代理,
- HttpHost proxy = new HttpHost("10.36.24.3", 60001);
- httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
- HttpClient httpClient = new DefaultHttpClient(cm, httpParams);
自动重连
如果某次请求请求失败,可以自动重连
- DefaultHttpClient httpClient = new DefaultHttpClient();
- // 可以自动重连
- HttpRequestRetryHandler requestRetryHandler2 = new HttpRequestRetryHandler() {
- // 自定义的恢复策略
- public synchronized boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
- // 设置恢复策略,在发生异常时候将自动重试3次
- if (executionCount > 3) {
- // 超过最大次数则不需要重试
- return false;
- }
- if (exception instanceof NoHttpResponseException) {
- // 服务停掉则重新尝试连接
- return true;
- }
- if (exception instanceof SSLHandshakeException) {
- // SSL异常不需要重试
- return false;
- }
- HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
- boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
- if (!idempotent) {
- // 请求内容相同则重试
- return true;
- }
- return false;
- }
- };
- httpClient.setHttpRequestRetryHandler(requestRetryHandler2);
使用自定义ResponseHandler处理返回的请求
- HttpClient httpClient = new DefaultHttpClient();
- HttpGet get = new HttpGet(url);
- // 定义一个类处理URL返回的结果
- ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
- public byte[] handleResponse(HttpResponse response)
- throws ClientProtocolException, IOException {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- return EntityUtils.toByteArray(entity);
- } else {
- return null;
- }
- }
- };
- // 不同于 httpClient.execute(request),返回值是HttpResponse;返回值右ResponseHandler决定
- byte[] charts = httpClient.execute(get, handler);
- FileOutputStream out = new FileOutputStream(fileName);
- out.write(charts);
- out.close();
- httpClient.getConnectionManager().shutdown();
参考文献
HttpClient学习系列 -- 学习总结的更多相关文章
- Identity Server4学习系列四之用户名密码获得访问令牌
1.简介 Identity Server4支持用户名密码模式,允许调用客户端使用用户名密码来获得访问Api资源(遵循Auth 2.0协议)的Access Token,MS可能考虑兼容老的系统,实现了这 ...
- Identity Server4学习系列三
1.简介 在Identity Server4学习系列一和Identity Server4学习系列二之令牌(Token)的概念的基础上,了解了Identity Server4的由来,以及令牌的相关知识, ...
- SpringCloud学习系列之七 ----- Zuul路由网关的过滤器和异常处理
前言 在上篇中介绍了SpringCloud Zuul路由网关的基本使用版本,本篇则介绍基于SpringCloud(基于SpringBoot2.x,.SpringCloud Finchley版)中的路由 ...
- 分布式学习系列【dubbo入门实践】
分布式学习系列[dubbo入门实践] dubbo架构 组成部分:provider,consumer,registry,monitor: provider,consumer注册,订阅类似于消息队列的注册 ...
- Entity Framework Code First学习系列目录
Entity Framework Code First学习系列说明:开发环境为Visual Studio 2010 + Entity Framework 5.0+MS SQL Server 2012, ...
- WCF学习系列汇总
最近在学习WCF,打算把一整个系列的文章都”写“出来,包括理论和实践,这里的“写”是翻译,是国外的大牛写好的,我只是搬运工外加翻译.翻译的不好,大家请指正,谢谢了.如果觉得不错的话,也可以给我点赞,这 ...
- EF(Entity Framework)系统学习系列
好久没写博客了,继续开启霸屏模式,好了,废话不多说,这次准备重新系统学一下EF,一个偶然的机会找到了一个学习EF的网站(http://www.entityframeworktutorial.net/) ...
- MVC学习系列4--@helper辅助方法和用户自定义HTML方法
在HTML Helper,帮助类的帮助下,我们可以动态的创建HTML控件.HTML帮助类是在视图中,用来呈现HTML内容的.HTML帮助类是一个方法,它返回的是string类型的值. HTML帮助类, ...
- YYKit学习系列 ---- 开篇
准备花半年时间系统学习YYKit, 学习过程会放入"YYKit学习系列"这个分类, 喜欢YYKit的可以随时留意我的文章, 一起学习!!!
随机推荐
- Linux Shell Scripting Cookbook 读书笔记 7
ping, du, ps, kill, 收集系统信息 判断网络中哪些主机是活动主机 #!/bin/bash for ip in 10.215.70.{1..255}; do ( ping $ip -c ...
- VCRuntime静默安装
批处理脚本: "%~dp0\VC_X64Runtime\VC_x64Runtime.exe" /q"%~dp0\VC_X86Runtime\VC_X86Runtime.e ...
- Codeforces Round #445
ACM ICPC 每个队伍必须是3个人 #include<stdio.h> #include<string.h> #include<stdlib.h> #inclu ...
- html行级元素和块级元素以及css转换
之前有说过html的标签是有语义的,当然也就有一些默认的样式,比如标题有h1···h6,他们的字体由大至小一次递减,字体比一般字体要加粗. 这样也就有了行级元素和块级元素,下面来看看什么是行级元素什么 ...
- java网络编程之socket(1)
网络编程是什么 网络编程的本质是两个设备之间的数据交换,当然,在计算机网络中,设备主要指计算机.数据传递本身没有多大的难度,不就是把一个设备中的数据发送给两外一个设备,然后接受另外一个设备反馈的数据. ...
- Windows2012R2 时间同步设置
Windows2012R2里没有了internet时间,或者Internet时间无法同步成功,都可以尝试使用如下方法. 1.打开命令提示符, 输入:gpedit.msc,打开组策略管理器 2.执行上述 ...
- Boost1.67编译+CMake Generate时遇到的一个错误
下载的一个库编译时依赖boost,记录一下boost的编译: 下载源码 vs命令行里cd到根目录,运行bootstrap.bat,发现多了几个文件{b2.exe.bjam.exe.project-co ...
- Linux 内核剖解(转)
Linux 内核剖析(转) linux内核是一个庞大而复杂的操作系统的核心,不过尽管庞大,但是却采用子系统和分层的概念很好地进行了组织.在本文中,您将探索 Linux 内核的总体结构,并学习一些主要 ...
- python入门基础知识
1.python环境的安装 python2 python3 安装后添加环境变量 2.编码 最早编码ASCII码,主要有英文,数字,字符.一字节(byte),八位(bit),代表一个字符 unicode ...
- 自动化构建之bower
官网地址:https://bower.io/ 网站由很多东西组成 - 框架,库,一个大型网站有很多人一块创建,那么因为版本或者其他的原因导致文件重复,或者不是最新的.例如:jq的版本不一样但是都是jq ...