博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpClient4.3 教程 第五章 快速API
阅读量:6687 次
发布时间:2019-06-25

本文共 3464 字,大约阅读时间需要 11 分钟。

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
() { 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); } } });

 

转载请保留链接地址: 

转载于:https://www.cnblogs.com/shareshow/p/4785264.html

你可能感兴趣的文章
Javascript如何实现GPU加速?
查看>>
次世代的会话管理项目 Spring Session
查看>>
SQL SERVER 2008安全配置
查看>>
Json hijacking/Json劫持漏洞
查看>>
算法知识梳理(5) 数组第二部分
查看>>
多页应用增量更新静态资源Webpack打包方案
查看>>
ionic V3.3开发踩坑集锦
查看>>
Realm入门指北
查看>>
彻底搞懂Bean加载
查看>>
iOS之传值
查看>>
技术blog 迁移
查看>>
linux 定时器怎么用? crontab 基础
查看>>
React Native - Image
查看>>
Docker和宿主机操作系统文件目录互相隔离的实现原理
查看>>
小程序踩坑系列一
查看>>
探索webpack热更新对代码打包结果的影响(二)
查看>>
微信小程序_豆瓣电影
查看>>
记一次网络模块的小规模重构
查看>>
FMI-人工智能&大数据高峰论坛(深圳站)
查看>>
区块链简单研读笔记
查看>>