Friday, 23 October 2015

HTTP Client: get response body


HttpResponse class provides getEntity method to get the message entity of the response. Following application get all the contents from url ‘https://self-learning-java-tutorial.blogspot.com’.

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.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class Main {

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

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(uri);
    CloseableHttpResponse response = httpclient.execute(httpget);

    HttpEntity entity = response.getEntity();

    if (entity != null) {
      InputStream instream = entity.getContent();
      BufferedReader br = new BufferedReader(new InputStreamReader(
          instream));

      try {
        String data;
        while ((data = br.readLine()) != null) {
          System.out.println(data);
        }
      } finally {
        instream.close();
      }
    }

    response.close();
  }
}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment