`

HttpClient4.3 教程 第五章 快速API

 
阅读更多

 

5.1.Easy to use facade API

HttpClient从4.2开始支持快速api。快速api仅仅实现了HttpClient的基本功能,它只要用于一些不需要灵活性的简单场景。例如,快速api不需要用户处理连接管理和资源释放。

下面是几个使用快速api的例子:

    // 执行一个get方法,设置超时时间,并且将结果变成字符串
    Request.Get("http://www.yeetrack.com/")
            .connectTimeout(1000)
            .socketTimeout(1000)
            .execute().returnContent().asString();

    // 使用HTTP/1.1,通过'expect-continue' handshake来执行post方法
    // 内容包含一个字符串,并且将结果转化成byte数组
    Request.Post("http://www.yeetrack.com/do-stuff")
        .useExpectContinue()
        .version(HttpVersion.HTTP_1_1)
        .bodyString("Important stuff", ContentType.DEFAULT_TEXT)
        .execute().returnContent().asBytes();

    // 通过代理服务器来执行一个带有特殊header的post请求,post请求中带有form表单,并且将返回结果写入文件
    Request.Post("http://www.yeetrack.com/some-form")
            .addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
            .execute().saveContent(new File("result.dump"));

如果需要在指定的安全上下文中执行某些请求,我们也可以直接使用Exector,这时候用户的认证信息就会被缓存起来,以便后续的请求使用。

    Executor executor = Executor.newInstance()
            .auth(new HttpHost("somehost"), "username", "password")
            .auth(new HttpHost("myproxy", 8080), "username", "password")
            .authPreemptive(new HttpHost("myproxy", 8080));

    executor.execute(Request.Get("http://somehost/"))
            .returnContent().asString();

    executor.execute(Request.Post("http://somehost/do-stuff")
            .useExpectContinue()
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT))
            .returnContent().asString();

5.1.1.响应处理

一般情况下,HttpClient的快速api不用用户处理连接管理和资源释放。但是,这样的话,就必须在内存中缓存这些响应消息。为了避免这一情况,建议使用使用ResponseHandler来处理Http响应。

    Document result = Request.Get("http://somehost/content")
            .execute().handleResponse(new ResponseHandler<Document>() {

        public Document handleResponse(final HttpResponse response) throws IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(
                        statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                ContentType contentType = ContentType.getOrDefault(entity);
                if (!contentType.equals(ContentType.APPLICATION_XML)) {
                    throw new ClientProtocolException("Unexpected content type:" +
                        contentType);
                }
                String charset = contentType.getCharset();
                if (charset == null) {
                    charset = HTTP.DEFAULT_CONTENT_CHARSET;
                }
                return docBuilder.parse(entity.getContent(), charset);
            } catch (ParserConfigurationException ex) {
                throw new IllegalStateException(ex);
            } catch (SAXException ex) {
                throw new ClientProtocolException("Malformed XML document", ex);
            }
        }

        });

 

分享到:
评论
1 楼 李嘉图0624 2015-05-17  
很好,就是我还是有些地方看不懂

相关推荐

    HttpClient以及获取页面内容应用

    压缩包中含有多个文档,从了解httpclient到应用。 httpClient 1httpClint 1.1简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持...

    Android开发案例驱动教程 配套代码

    第5章 UI基础控件 61 5.1 按钮 61 5.1.1 Button 62 5.1.2 ImageButton 63 5.1.3 ToggleButton 64 5.2 TextView 64 5.3 EditText 65 5.4 RadioButton和RadioGroup 66 5.4.1 RadioButton 66 5.4.2 RadioGroup...

    疯狂Android讲义(第2版)源代码 第6章~第9章

    第5章、使用Intent和IntentFilter进行通信 5.1、Intent对象详解: 5.2、Intent的属性及intent-filter配置:Component属性; Action、Category属性与intent-filter配置; Data、Type属性与intent-filter配置; ...

    Android典型技术模块开发详解

    第5章 BroadcastReceiver (广播) 5.1 生命周期 5.2 广播类型 5.2.1 普通广播 5.2.2 有序广播 5.2.3 异步广播 5.3 系统广播应用 5.3.1 系统广播 5.3.2 开机启动程序 5.3.3 电量监测 5.4 本章小结 第6章 Service...

    Android实例代码

    第5章、使用Intent和IntentFilter进行通信 5.1、Intent对象详解: 5.2、Intent的属性及intent-filter配置:Component属性; Action、Category属性与intent-filter配置; Data、Type属性与intent-filter配置; Extra...

    精通ANDROID 3(中文版)1/2

    第5章 Intent  5.1 Android Intent基础知识  5.2 Android中可用的Intent  5.3 Intent的组成  5.3.1 Intent和数据URI  5.3.2 一般操作  5.3.3 使用extra信息  5.3.4 使用组件直接调用活动  5.3.5 ...

    精通Android 3 (中文版)2/2

    第5章 Intent  5.1 Android Intent基础知识  5.2 Android中可用的Intent  5.3 Intent的组成  5.3.1 Intent和数据URI  5.3.2 一般操作  5.3.3 使用extra信息  5.3.4 使用组件直接调用活动  5.3.5 ...

    疯狂Android讲义源码

     第5章 使用Intent和IntentFilter  第5章 进行通信 196  5.1 Intent对象详解 197  5.1.1 使用Intent启动系统组件 197  5.2 Intent的属性及intent-filter  配置 198  5.2.1 Component属性 198  5.2.2 Action...

    疯狂Android讲义.part2

    第5章 使用Intent和IntentFilter 第5章 进行通信 196 5.1 Intent对象详解 197 5.1.1 使用Intent启动系统组件 197 5.2 Intent的属性及intent-filter 配置 198 5.2.1 Component属性 198 5.2.2 Action、Category属性与 ...

    疯狂Android讲义.part1

    第5章 使用Intent和IntentFilter 第5章 进行通信 196 5.1 Intent对象详解 197 5.1.1 使用Intent启动系统组件 197 5.2 Intent的属性及intent-filter 配置 198 5.2.1 Component属性 198 5.2.2 Action、Category属性与 ...

    大型分布式网站架构与实践

     第5章 数据分析 337  本章主要介绍和解决如下问题:  分布式系统中日志收集系统的架构。  如何通过Storm进行实时的流式数据分析。  如何通过Hadoop进行离线数据分析,通过Hive建立数据仓库。  如何将关系型...

    OPhone应用开发权威指南(黄晓庆)

    第5章 OpenGL ES编程 162 5.1 OpenGL ES概述 162 5.1.1 OpenGL ES设计准则 162 5.1.2 OpenGL ES 与OpenGL的不同 163 5.1.3 一个简单的OpenGL ES程序 166 5.2 3D观察与变换 169 5.2.1 一个简单的例子:绘制立方体 169...

    低清版 大型门户网站是这样炼成的.pdf

    第5章 hibernate 3持久化技术实践与性能优化 271 5.1 操作持久化对象的常用方法介绍 271 5.1.1 使用session的begintransaction()方法 272 5.1.2 使用session的close()方法 273 5.1.3 使用session的connection()...

    开涛高可用高并发-亿级流量核心技术

    第1部分概述 1 1 交易型系统设计的一些原则 2 1.1 高并发原则 3 1.1.1 无状态 3 1.1.2 拆分 3 1.1.3 服务化 4 1.1.4 消息队列 4 1.1.5 数据异构 6 1.1.6 缓存银弹 7 1.1.7 并发化 9 1.2 高可用原则 10 1.2.1 降级 10...

Global site tag (gtag.js) - Google Analytics