HttpClient4.2 Fluent API学习
相比于HttpClient 之前的版本,HttpClient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的API,即Fluent API. 为了方便使用,Fluent API只暴露了一些最基本的HttpClient功能。这样,Fluent API就将开发者从连接管理、资源释放等繁杂的操作中解
相比于HttpClient 之前的版本,HttpClient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的API,即Fluent API.
为了方便使用,Fluent API只暴露了一些最基本的HttpClient功能。这样,Fluent API就将开发者从连接管理、资源释放等繁杂的操作中解放出来,从而更易进行一些HttpClient的简单操作。
http://blog.csdn.net/vector_yi/article/details/24298629
还是利用具体例子来说明吧。
以下是几个使用Fluent API的代码样例:
一、最基本的http请求功能
执行Get、Post请求,不对返回的响应作处理
package com.vectoryi.fluent; import java.io.File; import org.apache.http.HttpHost; import org.apache.http.HttpVersion; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; import org.apache.http.entity.ContentType; public class FluentRequests { public static void main(String[] args)throws Exception { //执行一个GET请求,同时设置Timeout参数并将响应内容作为String返回 Request.Get("http://blog.csdn.net/vector_yi") .connectTimeout(1000) .socketTimeout(1000) .execute().returnContent().asString(); //以Http/1.1版本协议执行一个POST请求,同时配置Expect-continue handshake达到性能调优, //请求中包含String类型的请求体并将响应内容作为byte[]返回 Request.Post("http://blog.csdn.net/vector_yi") .useExpectContinue() .version(HttpVersion.HTTP_1_1) .bodyString("Important stuff", ContentType.DEFAULT_TEXT) .execute().returnContent().asBytes(); //通过代理执行一个POST请求并添加一个自定义的头部属性,请求包含一个HTML表单类型的请求体 //将返回的响应内容存入文件 Request.Post("http://blog.csdn.net/vector_yi") .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")); } }
二、在后台线程中异步执行多个请求
package com.vectoryi.fluent; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.http.client.fluent.Async; import org.apache.http.client.fluent.Content; import org.apache.http.client.fluent.Request; import org.apache.http.concurrent.FutureCallback; public class FluentAsync { public static void main(String[] args)throws Exception { // 利用线程池 ExecutorService threadpool = Executors.newFixedThreadPool(2); Async async = Async.newInstance().use(threadpool); Request[] requests = new Request[] { Request.Get("http://www.google.com/"), Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"), Request.Get("http://www.apple.com/") }; Queue<future>> queue = new LinkedList<future>>(); // 异步执行GET请求 for (final Request request: requests) { Future<content> future = async.execute(request, new FutureCallback<content>() { public void failed(final Exception ex) { System.out.println(ex.getMessage() + ": " + request); } public void completed(final Content content) { System.out.println("Request completed: " + request); } public void cancelled() { } }); queue.add(future); } while(!queue.isEmpty()) { Future<content> future = queue.remove(); try { future.get(); } catch (ExecutionException ex) { } } System.out.println("Done"); threadpool.shutdown(); } }</content></content></content></future></future>
三、更快速地启动请求
package com.vectoryi.fluent; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; public class FluentQuickStart { public static void main(String[] args) throws Exception { Request.Get("http://targethost/homepage") .execute().returnContent(); Request.Post("http://targethost/login") .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()) .execute().returnContent(); } }
四、处理Response
在本例中是利用xmlparsers来解析返回的ContentType.APPLICATION_XML类型的内容。
package com.vectoryi.fluent; import java.io.IOException; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.fluent.Request; import org.apache.http.entity.ContentType; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class FluentResponseHandling { public static void main(String[] args)throws Exception { Document result = Request.Get("http://www.baidu.com") .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); } Charset charset = contentType.getCharset(); if (charset == null) { charset = Consts.ISO_8859_1; } return docBuilder.parse(entity.getContent(), charset.name()); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } catch (SAXException ex) { throw new ClientProtocolException("Malformed XML document", ex); } } }); // 处理得到的result System.out.println(result); } }</document>

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

学习C语言的魅力:解锁程序员的潜力随着科技的不断发展,计算机编程已经成为了一个备受关注的领域。在众多编程语言中,C语言一直以来都备受程序员的喜爱。它的简单、高效以及广泛应用的特点,使得学习C语言成为了许多人进入编程领域的第一步。本文将讨论学习C语言的魅力,以及如何通过学习C语言来解锁程序员的潜力。首先,学习C语言的魅力在于其简洁性。相比其他编程语言而言,C语

从零开始学习Pygame:完整的安装和配置教程,需要具体代码示例引言:Pygame是一个使用Python编程语言开发的开源游戏开发库,它提供了丰富的功能和工具,使得开发者可以轻松创建各种类型的游戏。本文将带您从零开始学习Pygame,并提供完整的安装和配置教程,以及具体的代码示例,让您快速入门。第一部分:安装Python和Pygame首先,确保您的计算机上已

在word中编辑文字内容时,有时会需要输入公式符号。有的小伙们不知道在word根号输入的方法,小面就让小编跟小伙伴们一起分享下word根号输入的方法教程。希望对小伙伴们有所帮助。首先,打开电脑上的Word软件,然后打开要编辑的文件,并将光标移动到需要插入根号的位置,参考下方的图片示例。2.选择【插入】,再选择符号里的【公式】。如下方的图片红色圈中部分内容所示:3.接着选择下方的【插入新公式】。如下方的图片红色圈中部分内容所示:4.选择【根式】,再选择合适的根号。如下方的图片红色圈中部分内容所示:

Oracle是一家全球知名的数据库管理系统提供商,其API(ApplicationProgrammingInterface,应用程序接口)是一种强大的工具,可帮助开发人员轻松地与Oracle数据库进行交互和集成。在本文中,我们将深入探讨OracleAPI的使用指南,向读者展示如何在开发过程中利用数据接口技术,同时提供具体的代码示例。1.Oracle

OracleAPI集成策略解析:实现系统间无缝通信,需要具体代码示例在当今数字化时代,企业内部系统之间需要相互通信和数据共享,而OracleAPI就是帮助实现系统间无缝通信的重要工具之一。本文将从OracleAPI的基本概念和原理入手,探讨API集成的策略,最终给出具体的代码示例帮助读者更好地理解和应用OracleAPI。一、OracleAPI基本

标题:如何处理LaravelAPI报错问题,需要具体代码示例在进行Laravel开发时,经常会遇到API报错的情况。这些报错可能来自于程序代码逻辑错误、数据库查询问题或是外部API请求失败等多种原因。如何处理这些报错是一个关键的问题,本文将通过具体的代码示例来演示如何有效处理LaravelAPI报错问题。1.错误处理在Laravel

标题:从零开始学习Go语言中的main函数Go语言作为一种简洁、高效的编程语言,备受开发者青睐。在Go语言中,main函数是一个入口函数,每个Go程序都必须包含main函数作为程序的入口点。本文将从零开始介绍如何学习Go语言中的main函数,并提供具体的代码示例。一、首先,我们需要安装Go语言的开发环境。可以前往官方网站(https://golang.org

原文作者:Minty,加密KOL原文编译:深潮TechFlow如果您知道如何使用,Dune就是一款一体化的alpha工具。使用下面这20个Dune仪表板提升您的研究水平。1.TopHolder分析这个简洁工具由@dcfpascal开发,可以根据持有人的每月活动、唯一持有人数量和钱包盈亏比等指标进行代币分析。访问链接:https://dune.com/dcfpascal/token-holders2.代币概览指标@andrewhong5297创建了这个仪表板,它提供了一种通过分析用户操作来评估代币
