博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【HttpClient4.5中文教程】十二.使用HttpClient流畅风格的API
阅读量:4291 次
发布时间:2019-05-27

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

HttpClient 4.2 中 简化了基于流畅风格的外观API。如果你不需要HttpClient丰富的灵活性,流畅风格API提供了HttpClient中最基础的方法,使用简单。比如:流畅风格API简化了使用者处理连接管理器和分配资源。

下面有几个例子:

// Execute a GET with timeout settings and return response content as String.Request.Get("http://somehost/")    .connectTimeout(1000)    .socketTimeout(1000)     .execute()    .returnContent().asString();

// Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,// containing a request body as String and return response content as byte array.Request.Post("http://somehost/do-stuff")    .useExpectContinue()    .version(HttpVersion.HTTP_1_1)    .bodyString("Important stuff", ContentType.DEFAULT_TEXT)    .execute().returnContent().asBytes();
// Execute a POST with a custom header through the proxy containing a request body// as an HTML form and save the result to the fileRequest.Post("http://somehost/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"));

你也可以直接使用Executor,以一个特定的安全上下文执行请求,这样认证信息就会进行缓存并再用于后续请求。

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

fluent facade API简化了使用者处理连接管理器和分配资源。在大多数情况下,它付出了在内存中缓存响应的代价。强烈建议使用ResponseHandler避免在内存中缓存响应。

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

转载地址:http://zihgi.baihongyu.com/

你可能感兴趣的文章
几种常用JSON库性能比较,为什么fastjson那么快
查看>>
再有人问你分布式锁,就把这个丢给他!
查看>>
Mysql优化小技巧
查看>>
Nginx作为缓存服务
查看>>
了解 Nginx 的基本概念
查看>>
count(*),count(1)和count(字段)的区别
查看>>
面试大杀器:为什么一定要用MQ中间件?
查看>>
漫谈 MySQL 的锁机制
查看>>
Java 中 long 和 double 的原子性?
查看>>
Nginx和Apache的对比
查看>>
一文带你看懂Spring事务!
查看>>
Spring Boot实战:拦截器与过滤器
查看>>
夯实基础:关于线程的Callable和Future两个类解析
查看>>
常用的设计模式汇总,超详细!
查看>>
一篇文章了解RPC框架原理
查看>>
技术进阶:ThreadPoolExecutor源码解析之机制原理篇
查看>>
nginx搭建简易负载均衡服务
查看>>
SpringCloud之Feign(Finchley版)
查看>>
应用框架:Spring IOC基于注解启动的分析
查看>>
基于注解@Aspect的AOP实现
查看>>