【HttpClient4.5中文教程】【第五章 :流式(链式)API】

【译者:fluent-我把它翻译为流式,facade-应该是使用了外观设计模式。】
5.1.简单 使用 facade API
HttpClient 4.2 中 简化了基于流式接口的外观API。流式外观API提供了HttpClient中最基础的方法,使用简单如果你不需要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 file
Request.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();


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


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

你可能感兴趣的:(【HttpClient4.5中文教程】【第五章 :流式(链式)API】)