RESTFul Java Consumer Producer Example

RESTFul Java Consumer Producer Example

In this example you will see how to create simple RESTFul service which will produce data and also create consumer which will consume data from exposed service:

  • Project structure:

RESTFul Java Consumer Producer Example

  • pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javahonk.resttempalte</groupId>
	<artifactId>RESTfulExample</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>REST Java Honks</name>
	<url>http://maven.apache.org</url>

	<repositories>
		<repository>
			<id>JBoss repository</id>
			<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>2.2.1.GA</version>
		</dependency>		

		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jackson-provider</artifactId>
			<version>2.2.1.GA</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>RESTfulExample</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>
  • web.xml:
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>REST Java Honk Test</display-name>

	<context-param>
		<param-name>resteasy.resources</param-name>
		<param-value>com.javahonk.resttemplate.StudentService</param-value>
	</context-param>

	<listener>
		<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
	</listener>
	
	<servlet>
		<servlet-name>javahonk-servlet</servlet-name>
		<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>javahonk-servlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

</web-app>
  • Model class: Student.java:
package com.javahonk.resttemplate;

public class Student {

	String name;
	int zip;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getZip() {
		return zip;
	}
	public void setZip(int zip) {
		this.zip = zip;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", zip=" + zip + "]";
	}
}
  • Service class: StudentService.java:
package com.javahonk.resttemplate;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/studentService")
public class StudentService {

	@GET
	@Path("/get")
	@Produces("application/json")
	public Student getProductInJSON() {

		Student student = new Student();
		student.setName("Java Honk");
		student.setZip(44003);
		
		return student; 

	}

	@POST
	@Path("/post")
	@Consumes("application/json")
	public Response createProductInJSON(Student product) {

		String result = "Successful : " + product;
		return Response.status(201).entity(result).build();
		
	}
	
}

To run this service you can use any server. I used tomcat server and to run right click StudentService.java –> Run on server (If you server set up done in eclipse)

  • Test get method call: TestGetCall.java:
package com.javahonk.client;

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

public class TestGetCall {

	public static void main(String[] args) {

		try {

			URL url = new URL("http://localhost:8080/RESTfulExample/studentService/get");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) 
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			

			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

			String output;
			while ((output = br.readLine()) != null) {

				System.out.println(output);
			}
			
			conn.disconnect();

		} catch (MalformedURLException e) {

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

			e.printStackTrace();
			
		}

	}

}
  • Test post call: TestPostCall.java:
package com.javahonk.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class TestPostCall {

	public static void main(String[] args) {

		try {

			URL url = new URL("http://localhost:8080/RESTfulExample/studentService/post");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/json");

			String input = "{\"zip\":10037,\"name\":\"Java Honk\"}";

			OutputStream os = conn.getOutputStream();
			os.write(input.getBytes());
			os.flush();

			if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) 
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			

			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

			String output;
			while ((output = br.readLine()) != null) {
				System.out.println(output);
			}

			conn.disconnect();

		} catch (MalformedURLException e) {

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

			e.printStackTrace();

		}

	}

}

Sample RESTFul consumer example which will consume date from outside:

  • CrunchTest.java:
package com.javahonk.client;

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

public class CrunchTest {

	public static void main(String[] args) {

		try {

			URL url = new URL("https://api.crunchbase.com/v/3/odm-organizations?user_key=38bfc645dcb86c44bb5fbec1984ba943");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();		
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

			String output;
			System.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null) {
				System.out.println(output);
			}			
			conn.disconnect();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();			
		}

	}

}
  • Sample consumer if you wanted to consumer service behind the firewall proxy.
package com.javahonk.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;

public class CrunchTestWithPass {

	public static void main(String[] args) {

		try {

			final String authUser = "user";
			final String authPassword = "pass";
			Authenticator.setDefault(new Authenticator() {
				@Override
				public PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(authUser, authPassword.toCharArray());
				}
			});

			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy name", 80));

			HttpURLConnection conn = (HttpURLConnection) new URL("http://api.crunchbase.com/v/3/odm-organizations?user_key=38bfc645dcb86c44bb5fbec1984ba943")
							.openConnection(proxy);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

			String output;
			System.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null) {
				System.out.println(output);
			}

			conn.disconnect();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *