Showing posts with label Apache Http Client. Show all posts
Showing posts with label Apache Http Client. Show all posts

Thursday, 14 March 2013

Java HttpURLConnection

Leave a Comment
Here's the source code for a complete Java class that demonstrates how to open a URL and then read from it, using the HttpURLConnection class. This class also demonstrates how to properly encode your URL using the encode method of the URLEncoder class.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 *
 * A complete Java class that shows how to open a URL, then read data (text) from that URL,
 * HttpURLConnection class (in combination with an InputStreamReader and BufferedReader).
 *
 * @author Harit Kumar
 *
 */
public class JavaHttpUrlConnectionReader
{
  public static void main(String[] args)
  throws Exception
  {
    new JavaHttpUrlConnectionReader();
  }
  
  public JavaHttpUrlConnectionReader()
  {
    try
    {
      String myUrl = "http://localhost:8080/";
      // if your url can contain weird characters you will want to 
      // encode it here, something like this:
      // myUrl = URLEncoder.encode(myUrl, "UTF-8");

      String results = doHttpUrlConnectionAction(myUrl);
      System.out.println(results);
    }
    catch (Exception e)
    {
      // deal with the exception in your "controller"
    }
  }

  
  /**
   * Returns the output from the given URL.
   * 
   * I tried to hide some of the ugliness of the exception-handling
   * in this method, and just return a high level Exception from here.
   * Modify this behavior as desired.
   * 
   * @param desiredUrl
   * @return
   * @throws Exception
   */
  private String doHttpUrlConnectionAction(String desiredUrl)
  throws Exception
  {
    URL url = null;
    BufferedReader reader = null;
    StringBuilder stringBuilder;

    try
    {
      // create the HttpURLConnection
      url = new URL(desiredUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      
      // just want to do an HTTP GET here
      connection.setRequestMethod("GET");
      
      // uncomment this if you want to write output to this url
      //connection.setDoOutput(true);
      
      // give it 15 seconds to respond
      connection.setReadTimeout(15*1000);
      connection.connect();

      // read the output from the server
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      stringBuilder = new StringBuilder();

      String line = null;
      while ((line = reader.readLine()) != null)
      {
        stringBuilder.append(line + "\n");
      }
      return stringBuilder.toString();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw e;
    }
    finally
    {
      // close the reader; this can throw an exception too, so
      // wrap it in another try/catch block.
      if (reader != null)
      {
        try
        {
          reader.close();
        }
        catch (IOException ioe)
        {
          ioe.printStackTrace();
        }
      }
    }
  }
}

Java HttpUrlConnection example - discussion

Here's a quick walk-through of how this Java HttpUrlConnection code works:
  1. The main method is called, and it creates a new instance of this class.
  2. I define a URL, pass that URL to the doHttpUrlConnectionAction method, then print the String output received from that method.
  3. The doHttpUrlConnectionAction method works like this:
    1. It creates a new URL.
    2. It opens a connection, then casts that connection to a HttpURLConnection.
    3. It sets the request method to GET (as opposed to something else, like POST).
    4. (Optional: The setDoOutput tells the object that we will be writing output to this URL.)
    5. I set the read timeout to 15 seconds, then ope the connection.
    6. I read the data as usual, using an  InputStreamReader and  BufferReader
    7. As I read each line of output from the URL, I add it to my  StringBuilder, then convert the StringBuilder to a  String when the method returns.
As mentioned, the setDoOutput method is optional. Here's a brief description of it from its Javadoc:
A URL connection can be used for input and/or output. Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.
In this example, because I'm not writing anything to the URL, I leave this set to its default value of false.
In summary, when you know that you are specifically dealing with an HTTP connection, the HttpURLConnection class offers many convenience methods and fields that can make your programming life a little easier.
Read More...

Wednesday, 13 March 2013

Apache HttpClient Get Post

Leave a Comment

1. Get Apache HttpClient

Apache HttpClient is available in Maven central repository, just declares it in your Maven pom.xml file.

File : pom.xml
 <dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.1.1</version>
 </dependency>

2. GET Request

Review last REST service again.
@Path("/json/product")
public class JSONService {
 
 @GET
 @Path("/get")
 @Produces("application/json")
 public Product getProductInJSON() {
 
  Product product = new Product();
  product.setName("iPad 3");
  product.setQty(999);
 
  return product; 
 
 }
 //...
 
Apache HttpClient to send a “GET” request.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
 
public class ApacheHttpClientGet {
 
 public static void main(String[] args) {
   try {
 
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpGet getRequest = new HttpGet(
   "http://localhost:8080/RESTfulExample/json/product/get");
  getRequest.addHeader("accept", "application/json");
 
  HttpResponse response = httpClient.execute(getRequest);
 
  if (response.getStatusLine().getStatusCode() != 200) {
   throw new RuntimeException("Failed : HTTP error code : "
      + response.getStatusLine().getStatusCode());
  }
 
  BufferedReader br = new BufferedReader(
                         new InputStreamReader((response.getEntity().getContent())));
 
  String output;
  System.out.println("Output from Server .... \n");
  while ((output = br.readLine()) != null) {
   System.out.println(output);
  }
 
  httpClient.getConnectionManager().shutdown();
 
   } catch (ClientProtocolException e) {
 
  e.printStackTrace();
 
   } catch (IOException e) {
 
  e.printStackTrace();
   }
 
 }
 
}
 
Output…
Output from Server .... 
 
{"qty":999,"name":"iPad 3"}

3. POST Request

Review last REST service also.
@Path("/json/product")
public class JSONService {
 
        @POST
 @Path("/post")
 @Consumes("application/json")
 public Response createProductInJSON(Product product) {
 
  String result = "Product created : " + product;
  return Response.status(201).entity(result).build();
 
 }
 //...
 
 
 
Apache HttpClient to send a “POST” request.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
 
public class ApacheHttpClientPost {
 
 public static void main(String[] args) {
 
   try {
 
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpPost postRequest = new HttpPost(
   "http://localhost:8080/RESTfulExample/json/product/post");
 
  StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");
  input.setContentType("application/json");
  postRequest.setEntity(input);
 
  HttpResponse response = httpClient.execute(postRequest);
 
  if (response.getStatusLine().getStatusCode() != 201) {
   throw new RuntimeException("Failed : HTTP error code : "
    + response.getStatusLine().getStatusCode());
  }
 
  BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
 
  String output;
  System.out.println("Output from Server .... \n");
  while ((output = br.readLine()) != null) {
   System.out.println(output);
  }
 
  httpClient.getConnectionManager().shutdown();
 
   } catch (MalformedURLException e) {
 
  e.printStackTrace();
 
   } catch (IOException e) {
 
  e.printStackTrace();
 
   }
 
 }
 
}
 
Output…
Output from Server .... 
 
Product created : Product [name=iPad 4, qty=100]
Read More...

Apache HttpClient

Leave a Comment

1. Using the Apache HttpClient

The Apache HttpClient library simplifies handling HTTP requests. To use this library download the binaries with dependencies from http://hc.apache.org/ and add then to your project class path.
You retrieve and send data via the HttpClient class. An instance of this class can be created with new DefaultHttpClient();
DefaultHttpClient is the standard HttpClient and uses the SingleClientConnManager class to handle HTTP connections. SingleClientConnManager is not thread-safe, this means that access to it via several threads will create problems.
The HttpClient uses a HttpUriRequest to send and receive data. Important subclass of HttpUriRequest are HttpGet and HttpPost. You can get the response of the HttpClient as an InputStream.

2. Examples

2.1. Project and Expectations

The following examples do not necessary work out of the box as we do not provide the required backend for receiving the data. Think of the following as examples how to setup HttpClients. Download the HttpClient libraries from the Apache Website, you can download the "bin" package it includes all dependencies.
Create a new Java project , and add them to the path of your Java project. We use the project for creating our tests.

2.2. Http Get

The following is an example an HTTP Get request via HttpClient.

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.javaguide.com");
HttpResponse response = client.execute(request);

// Get the response
BufferedReader rd = new BufferedReader
  (new InputStreamReader(response.getEntity().getContent()));
    
String line = "";
while ((line = rd.readLine()) != null) {
  textView.append(line);
} 

2.3. Http Post

The following will send a post request to the URL "http://javaguide.blog.com/register" and include a parameter "registrationid" which an random value.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class SimpleHttpPut { 
  public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://javaguide.blog.com/register");
    try {
      List nameValuePairs = new ArrayList(1);
      nameValuePairs.add(new BasicNameValuePair("registrationid",
          "123456789"));
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 
      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
The following request adds several parameters to the post request.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class TestHttpClient {
  public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

    try {

      List nameValuePairs = new ArrayList(1);
      nameValuePairs.add(new BasicNameValuePair("Email", "youremail"));
      nameValuePairs
          .add(new BasicNameValuePair("Passwd", "yourpassword"));
      nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
      nameValuePairs.add(new BasicNameValuePair("source",
          "Google-cURL-Example"));
      nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
        if (line.startsWith("Auth=")) {
          String key = line.substring(5);
          // Do something with the key
        }

      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
} 
Read More...

REST WebService Clients

Leave a Comment
Using a Web Browser as the Client

The easiest way to test our RESTful service is using your favourite web browser.  Simply enter the URL and the browser will render the result as XML.


Using Java SE

There currently isn't a standard set of APIs yet for interacting with JAX-RS.  However your Java SE install already has all the necessary APIs.
String uri = 
    "http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection = 
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer = 
    (Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();
Using Implmentation Specific APIs 

 While there isn't a standard set of APIs to interact with JAX-RS services, implementations like Jersey do provide APIs that are easier to use than standard Java SE.
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.example.Customer;
import com.sun.jersey.api.client.*;

public class JerseyClient {

    public static void main(String[] args) {
        Client client = Client.create();
        WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers");

        // Get response as String
        String string = resource.path("1")
            .accept(MediaType.APPLICATION_XML)
                .get(String.class);
        System.out.println(string);

        // Get response as Customer
        Customer customer = resource.path("1")
            .accept(MediaType.APPLICATION_XML)
                .get(Customer.class);
        System.out.println(customer.getLastName() + ", "+ customer.getFirstName());

        // Get response as List
        List customers = resource.path("findCustomersByCity/Any%20Town")
            .accept(MediaType.APPLICATION_XML)
                .get(new GenericType>(){});
        System.out.println(customers.size());
    }

}

Read More...