您的位置:首页 > 理论基础 > 计算机网络

HttpClient 4.3详细教程之快速API

2017-07-14 15:27 344 查看


5.1. Easy to use facade API

HttpClient从4.2开始支持快速api。快速api仅仅实现了HttpClient的基本功能,它只要用于一些不需要灵活性的简单场景。例如,快速api不需要用户处理连接管理和资源释放。

下面是几个使用快速api的例子:

[java] view
plaincopy

// Execute a GET with timeout settings and return response content as String.  

Request.Get("http://somehost/")  

        .connectTimeout(1000)  

        .socketTimeout(1000)  

        .execute().returnContent().asString();  

[java] view
plaincopy

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

[java] view
plaincopy

// 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"));  

如果需要在指定的安全上下文中执行某些请求,我们也可以直接使用Exector,这时候用户的认证信息就会被缓存起来,以便后续的请求使用。

[java] view
plaincopy

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.
响应处理

一般情况下,HttpClient的快速api不用用户处理连接管理和资源释放。但是,这样的话,就必须在内存中缓存这些响应消息。为了避免这一情况,建议使用使用ResponseHandler来处理Http响应。

[java] view
plaincopy

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

        }  

    }  

  

    });  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: