HttpClient4.3 tutorial Chapter 5 quick API

Posted by Blesbok on Tue, 05 May 2020 01:36:01 +0200

5.1.Easy to use facade API

HttpClient supports fast api from 4.2. The fast api only implements the basic functions of HttpClient, and it only needs to be used in some simple scenarios without flexibility. For example, a fast api does not require users to handle connection management and resource release.

Here are a few examples of using the fast api:

    // Execute a get method, set the timeout, and change the result to a string
    Request.Get("http://www.yeetrack.com/")
            .connectTimeout(1000)
            .socketTimeout(1000)
            .execute().returnContent().asString();

    // Use HTTP/1.1 to execute the post method through 'expect continue' handshake
    // The content contains a string and converts the result to a byte array
    Request.Post("http://www.yeetrack.com/do-stuff")
        .useExpectContinue()
        .version(HttpVersion.HTTP_1_1)
        .bodyString("Important stuff", ContentType.DEFAULT_TEXT)
        .execute().returnContent().asBytes();

    // A post request with a special header is executed through the proxy server. The form form is included in the post request, and the returned result is written to the file
    Request.Post("http://www.yeetrack.com/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"));

If we need to execute some requests in the specified security context, we can also directly use the executor, at this time, the user's authentication information will be cached for subsequent requests.

    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. Response processing

In general, HttpClient's fast api does not require users to handle connection management and resource release. However, in this way, these response messages must be cached in memory. To avoid this, it is recommended to use the ResponseHandler to handle Http responses.

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

        });

Source of HttpClient document translation


Topics: xml