Friday 23 October 2015

HTTP Client: generate URI using URIBuilder

Apache HTTP client provides URIBuilder class, to construct uri in friendly manner. URI is used to identify the name of a resource. Generayyly URI looks like below.

scheme:[//[user:password@]domain[:port]][/]path[?query][#fragment]
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

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.client.utils.URIBuilder;
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, URISyntaxException {
    URI uri = new URIBuilder().setScheme("http").setHost("www.google.com")
        .setPath("/search")
        .setParameter("q", "self learning java blog").build();

    System.out.println(uri);

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

    printResponse(response);

    response.close();
  }
}


Output
http://www.google.com/search?q=self+learning+java+blog
HTTP/1.1
200
OK
HTTP/1.1 200 OK



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment