Friday 23 October 2015

HTTP Client: Response Handlers


By using ResponseHandler interface, you can handle responses conveniently. ResponseHandler interface includes the handleResponse(HttpResponse response) method. This method completely relieves the user from having to worry about connection management. When using a ResponseHandler, HttpClient will automatically take care of ensuring release of the connection back to the connection manager regardless whether the request execution succeeds or causes an exception.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

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.HttpClientBuilder;

public class Main {

  public static void main(String args[]) throws ClientProtocolException,
      IOException, URISyntaxException {
    String uri = "https://self-learning-java-tutorial.blogspot.com";

    HttpGet httpget = new HttpGet(uri);

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

      @Override
      public String handleResponse(HttpResponse response)
          throws ClientProtocolException, IOException {
        HttpEntity entity = response.getEntity();

        InputStream instream = entity.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(
            instream));

        StringBuilder builder = new StringBuilder();
        try {
          String data;
          while ((data = br.readLine()) != null) {
            builder.append(data).append("\n");
          }
          return builder.toString();
        } finally {
          instream.close();
        }
      }

    };

    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    String result = httpclient.execute(httpget, responseHandler);
    System.out.println(result);
  }
}




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment