Home Database Mysql Tutorial HttpClient4.2 Fluent API学习

HttpClient4.2 Fluent API学习

Jun 07, 2016 pm 03:32 PM
api fluent study

相比于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"));
    }

}
Copy after login

二、在后台线程中异步执行多个请求
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>
Copy after login

三、更快速地启动请求
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();
    }
}
Copy after login

四、处理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>
Copy after login



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Revealing the appeal of C language: Uncovering the potential of programmers Revealing the appeal of C language: Uncovering the potential of programmers Feb 24, 2024 pm 11:21 PM

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Feb 19, 2024 pm 10:10 PM

Learn Pygame from scratch: complete installation and configuration tutorial, specific code examples required Introduction: Pygame is an open source game development library developed using the Python programming language. It provides a wealth of functions and tools, allowing developers to easily create a variety of type of game. This article will help you learn Pygame from scratch, and provide a complete installation and configuration tutorial, as well as specific code examples to get you started quickly. Part One: Installing Python and Pygame First, make sure you have

Let's learn how to input the root number in Word together Let's learn how to input the root number in Word together Mar 19, 2024 pm 08:52 PM

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Learn the main function in Go language from scratch Learn the main function in Go language from scratch Mar 27, 2024 pm 05:03 PM

Title: Learn the main function in Go language from scratch. As a simple and efficient programming language, Go language is favored by developers. In the Go language, the main function is an entry function, and every Go program must contain the main function as the entry point of the program. This article will introduce how to learn the main function in Go language from scratch and provide specific code examples. 1. First, we need to install the Go language development environment. You can go to the official website (https://golang.org

Understand these 20 Dune analysis dashboards and quickly capture trends on the chain Understand these 20 Dune analysis dashboards and quickly capture trends on the chain Mar 13, 2024 am 09:19 AM

Original author: Minty, encryption KOL Original compilation: Shenchao TechFlow If you know how to use it, Dune is an all-in-one alpha tool. Take your research to the next level with these 20 Dune dashboards. 1. TopHolder Analysis This simple tool developed by @dcfpascal can analyze tokens based on indicators such as holders’ monthly activity, number of unique holders, and wallet profit and loss ratio. Visit link: https://dune.com/dcfpascal/token-holders2. Token Overview Metrics @andrewhong5297 created this dashboard which provides a way to evaluate tokens by analyzing user actions

See all articles