RSS

Tag Archives: restful web service

REST clients for Java, MySQL and JSON Restful Web Services

This is the second part of the tutorial which demonstrates Restful web service using Java, MySQL and JSON. In this tutorial we are going to create several REST clients for our web service. You can download each REST client project. Each REST client is going to parse the JSON response and display output.

Java REST client
Download
We use Java SE application as our client. To parse JSON, gson library is added to project /lib folder Also it is included in project build path as an external JAR.

Course.java – data bound model class

public class Course
{
private int id;
private String name;
private String duration;
private double fee;

public Course()
{

}

public Course(int id, String name, String duration, double fee)
{
super();
this.id = id;
this.name = name;
this.duration = duration;
this.fee = fee;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDuration()
{
return duration;
}

public void setDuration(String duration)
{
this.duration = duration;
}

public double getFee()
{
return fee;
}

public void setFee(double fee)
{
this.fee = fee;
}

@Override
public String toString()
{
return "Course [id=" + id + ", name=" + name + ", duration=" + duration
+ ", fee=" + fee + "]";
}

}

Main.java

package com;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class Main
{

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
String json = readUrl("http://localhost:8080/RestProject/Rest/courseService/courses");
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray courseArray = jsonParser.parse(json).getAsJsonArray();
List<Course> coursesList = new ArrayList<Course>();
for (JsonElement course : courseArray)
{
Course courseObj = gson.fromJson(course, Course.class);
coursesList.add(courseObj);
}

for (Course courseObj : coursesList)
{
System.out.println("ID : " + courseObj.getId());
System.out.println("Course Name : " + courseObj.getName());
System.out.println("Duration : " + courseObj.getDuration());
System.out.println("Course fee : " + courseObj.getFee());
}

}

private static String readUrl(String urlString) throws Exception
{
BufferedReader reader = null;
try
{
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);

return buffer.toString();
} finally
{
if (reader != null)
reader.close();
}

}
}

PHP REST client
CURL or file_get_contents() can be used to get JSON  from the web service URL.

$json = file_get_contents("http://localhost:8080/RestProject/Rest/courseService/courses");
$json_o = json_decode($json);

$msg .= "";
foreach($json_o as $item)
{
$msg .= "Course ID : ". $item->id. "<br>";
$msg .= "Course Name : ". $item->name. "<br>";
$msg .= "Duration  : ". $item->duration. "<br>";
$msg .= "Course fee : ". $item->fee. "<br><br>";
}
echo $msg;

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/RestProject/Rest/courseService/courses");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$json = curl_exec($ch);
$json_o = json_decode($json);

$msg .= "";
foreach($json_o as $item)
{
$msg .= "Course ID : ". $item->id. "<br>";
$msg .= "Course Name : ". $item->name. "<br>";
$msg .= "Duration  : ". $item->duration. "<br>";
$msg .= "Course fee : ". $item->fee. "<br><br>";
}
echo $msg;

Android REST client

Download


Advertisements
 
3 Comments

Posted by on November 28, 2012 in C#.Net, Java, PHP

 

Tags: ,

Restful Web Services Java, MySQL and JSON

Today we are going to build another restful web service in eclipse using gson library. When client makes a request, the application queries the database and produces response in JSON format. This JSON can be parsed with most of the programming languages.
We will see how various clients can consume this web service in the second part of the tutorial.

Download Source Code

Download Source Code
Project Architecture

Create a new dynamic web project in Eclipse and add jersy, gson library to WEB-INF/lib.

course.java
We utilize this class when we wanna bind data after querying database.

package dto;

public class Course
{
private int id;
private String name;
private String duration;
private double fee;

public Course()
{

}

public Course(int id, String name, String duration, double fee)
{
super();
this.id = id;
this.name = name;
this.duration = duration;
this.fee = fee;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDuration()
{
return duration;
}

public void setDuration(String duration)
{
this.duration = duration;
}

public double getFee()
{
return fee;
}

public void setFee(double fee)
{
this.fee = fee;
}

@Override
public String toString()
{
return "Course [id=" + id + ", name=" + name + ", duration=" + duration
+ ", fee=" + fee + "]";
}

}

 

Database.java

package dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class Database
{
public Connection getConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/codezone4";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
return connection;
} catch (Exception e)
{
throw e;
}

}

}

Access.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import dto.Course;

public class Access
{
public ArrayList<Course> getCourses(Connection con) throws SQLException
{
ArrayList<Course> courseList = new ArrayList<Course>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM courses");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Course courseObj = new Course();
courseObj.setId(rs.getInt("id"));
courseObj.setName(rs.getString("name"));
courseObj.setDuration(rs.getString("duration"));
courseObj.setFee(rs.getDouble("fee"));
courseList.add(courseObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return courseList;

}
}

AccessManager.java

package model;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import dao.Access;
import dao.Database;
import dto.Course;

public class AccessManager
{
public ArrayList<Course> getCourses() throws Exception
{
ArrayList<Course> courseList = new ArrayList<Course>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
courseList = access.getCourses(con);
return courseList;
}
}

CourseService.java

package webService;

import java.util.ArrayList;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import com.google.gson.Gson;

import model.AccessManager;

import dto.Course;

@Path("/courseService")
public class CourseService
{
@GET
@Path("/courses")
@Produces("application/json")
public String courses()
{
String courses = null;
ArrayList<Course> courseList = new ArrayList<Course>();
try
{
courseList = new AccessManager().getCourses();
Gson gson = new Gson();
courses = gson.toJson(courseList);
} catch (Exception e)
{
e.printStackTrace();
}
return courses;
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RestProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Course Service</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Course Service</servlet-name>
<url-pattern>/Rest/*</url-pattern>
</servlet-mapping>
</web-app>

Run the application in server.
visit following URL :
http://localhost:8440/RestProject/Rest/courseService/courses
The port number in the URL depends on your server settings.
You will see the JSON response.

 

Help make a developer’s life happy and strong.

Donate Button with Credit Cards

 
55 Comments

Posted by on November 8, 2012 in J2EE, Java

 

Tags: ,

Java Restful Web Services(JAX-RS) Using Jersy

This tutorial demonstrates how to build a Java Restful web service in Eclipse using Jersy plugin.

Download project

REST(Representational State Transfer) is an architectural style. This is not a standard whereas SOAP is standardized. RESTful web services are based on HTTP protocol and its methods PUT, GET, POST, and DELETE. They do not require XML SOAP messages or WSDL service definitions.

REST can be considered similar to a client-server architecture. There ‘s a REST server waiting for the requests from REST clients.

Requirements :

Main Topics
  1. Install Jersy plugin
  2. Create resource
  3. Create client
  4. Configure web.xml

1. Install Jersy plugin

Create new dynamic web project. Add  following jars from the downloaded Jersey zip file to WEB-INF/lib. Add them to project Build Path.

1. Create resource

package com.res;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

// This method is called if TEXT_PLAIN is request
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}

// This method is called if XMLis request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}

// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}

}

3. Create client

package com.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class client {

/**
* @param args
*/
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
// Fluent interfaces
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
// Get plain text
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
// Get XML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
// The HTML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));
}

private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8440/Success").build();
}

}

4. Configure web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Success</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.res</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

web.xml is tricky!
[Extracted from : http://www.javahotchocolate.com/tutorials/restful.html%5D
The display name. It can be anything, but it’s

what goes first thing in the URL (browser address

line) after the protocol (http) and domain-

name:port-number. Note that I’m not using

anything that looks like a package name here. I

don’t even have to use the Eclipse project name.

Obviously, it cannot contain a space.

The servlet name. It can have spaces in it, but it’s

used in another place and the two must be identical.

The servlet name doesn’t show up outside this file,

but this file uses it to find the appropriate mapping

definition.

The servlet container class. This pertains to the

framework you’re using. Here, we’re using Jersey, so

we’re sure to name that class which comes out of

the user library (set of Jersey JARs) we used.

The servlet container class parameter name, as

dictated (in this instance) by the REST servlet

container or framework in use.

The value of the preceding parameter. It must be

the package name that contains at least and at most

one (JAXB) servlet (.java file). There may be more

than one such servlet, but if so, the other(s) must be

in a different Java package.

The servlet name must be identical to the one

already specified above. As noted, if there are two

servlets, there are two servlet definitions and two,

separate servlet mapping definitions.

The URL pattern. It starts with ‘/’ and ends with

‘/*’ and can be any legitimate directory-like

identifier (without spaces). It is the penultimate

element of the URL, just before the class name path.

web.xml:



    Fun

	
    
        Jersey REST Service
        com.sun.jersey.spi.container.servlet.ServletCo

ntainer
        
            com.sun.jersey.config.property.packages

de.vogella.jersey.first 1 Fun with REST com.sun.jersey.spi.container.servlet.ServletCo ntainer com.sun.jersey.config.property.packages

com.etretatlogiciels.fun 1 Jersey REST Service /rest/* Fun with REST /fun/*
 
3 Comments

Posted by on November 5, 2012 in J2EE, Java

 

Tags: ,