use ResponseHandler to simplify processing the HTTP response and releasing associated resources. - Java Network

Java examples for Network:apache http

Description

use ResponseHandler to simplify processing the HTTP response and releasing associated resources.

Demo Code


import java.io.IOException;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**/*from w  w w .ja  va 2s . c  o  m*/
 * This example demonstrates the use of the {@link ResponseHandler} to simplify
 * the process of processing the HTTP response and releasing associated resources.
 */
public class Main {

    public final static void main(String[] args) throws Exception {



        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {

            HttpGet httpget = new HttpGet("https://your host");

            System.out.println("Executing request "
                    + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

                @Override
                public String handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils
                                .toString(entity) : null;
                    } else {
                        throw new ClientProtocolException(
                                "Unexpected response status: " + status);
                    }
                }

            };
            String responseBody = httpclient.execute(httpget,
                    responseHandler);
            System.out.println(responseBody);

        } finally {
            httpclient.close();
        }
    }

}

Related Tutorials