Showing posts with label Web Services. Show all posts
Showing posts with label Web Services. Show all posts

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