Friday 23 October 2015

HTTP Client: Sending simple GET Request

Following step-by-step procedure explains how to send simple HTTP GET request using Apache HTTP client.
Step 1: Create HTTP Client instance.
CloseableHttpClient httpclient = HttpClients.createDefault();

CloseableHttpClient is the base implementation of HttpClient.

Step 2: Create HTTP GET request by initializing HttpGet class.
HttpGet httpget = new HttpGet("https://self-learning-java-tutorial.blogspot.com");

Above snippet is used to send GET request to the URI https://self-learning-java-tutorial.blogspot.com. HTTPGet constructor throws IllegalArgumentException if the uri is invalid.

Step 3: Call execute method of httpclient.
CloseableHttpResponse response = httpclient.execute(httpget);

Above statement executes the httpget request.
Following is the complete working application.
import java.io.IOException;

import org.apache.http.HttpResponse;
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 printResponse(HttpResponse response) {
    System.out.println(response.getProtocolVersion());
    System.out.println(response.getStatusLine().getStatusCode());
    System.out.println(response.getStatusLine().getReasonPhrase());
    System.out.println(response.getStatusLine().toString());
  }

  public static void main(String args[]) throws ClientProtocolException,
      IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpGet httpget = new HttpGet(
        "https://self-learning-java-tutorial.blogspot.com");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
      printResponse(response);
    } finally {
      response.close();
    }
  }
}


Output
HTTP/1.1
200
OK
HTTP/1.1 200 OK



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment