HttpClient API 文档:5. 流式 API

5.1. 易于使用的门面 API

从 4.2 版本开始,HttpClient 提供了一个易于使用的基于流式接口概念的 facade API。暴露的流式 API(Fluent API) 接口仅仅是 HttpClient 最基本的一些功能,这些接口是在不需要使用 HttpClient 丰富的灵活性时,为了一些简单的功能而准备的。 例如,fluent facade API 使用户不必关心连接的管理和资源的释放。

下面是通过 HttpClient Fluent API 执行 HTTP 请求的几个例子:

// 执行具有超时设置的 GET 请求,并将响应内容返回为 String。
Request.Get("http://somehost/")
        .connectTimeout(1000)
        .socketTimeout(1000)
        .execute().returnContent().asString();
// 使用 HTTP/1.1 使用 “expect-continue” 握手执行 POST 请求,
// 其中包含一个请求主体作为字符串,并将响应内容返回为字节数组。
Request.Post("http://somehost/do-stuff")
        .useExpectContinue()
        .version(HttpVersion.HTTP_1_1)
        .bodyString("Important stuff", ContentType.DEFAULT_TEXT)
        .execute().returnContent().asBytes();
// 通过包含请求主体的代理以 HTML 形式执行带有自定义请求头的 POST 请求,
// 并将响应结果保存到文件中
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. 处理响应

流式 Facade 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);
        }
    }

    });

你可能感兴趣的:(HttpClient API 文档:5. 流式 API)