Wednesday, November 28, 2012

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

[sourcecode language="java"]
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 + "]";
}

}

[/sourcecode]

Main.java

[sourcecode language="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();
}

}
}

[/sourcecode]

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

[sourcecode language="php"]
$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;
[/sourcecode]

Android REST client

Download

[sourcecode language="java"]

[/sourcecode]

3 comments:

  1. Hello, sir i would like to ask that what is the scope of Php mysql training, what all topics should be covered and it is kinda bothering me … and has anyone studies from this course http://www.wiziq.com/course/5871-php-mysql-with-basic-javascript-integrated-course of core and advance java online ?? or tell me any other guidance...
    would really appreciate help… and Also i would like to thank for all the information you are providing on java concepts.

    ReplyDelete
  2. Hi Rajitha,
    Thank you for the tutorial, it is very useful. I tried your code but in the android client side when I click Launch button it gives me following error:


    2-17 15:40:20.551: D/AndroidRuntime(1677): Shutting down VM
    02-17 15:40:20.551: W/dalvikvm(1677): threadid=1: thread exiting with uncaught exception (group=0x41465700)
    02-17 15:40:20.571: E/AndroidRuntime(1677): FATAL EXCEPTION: main
    02-17 15:40:20.571: E/AndroidRuntime(1677): java.lang.NoClassDefFoundError: com.google.gson.Gson
    02-17 15:40:20.571: E/AndroidRuntime(1677): at com.example.rest.AndroidRestClientActivity$1.onClick(AndroidRestClientActivity.java:51)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at android.view.View.performClick(View.java:4240)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at android.view.View$PerformClick.run(View.java:17721)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at android.os.Handler.handleCallback(Handler.java:730)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at android.os.Handler.dispatchMessage(Handler.java:92)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at android.os.Looper.loop(Looper.java:137)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at android.app.ActivityThread.main(ActivityThread.java:5103)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at java.lang.reflect.Method.invokeNative(Native Method)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at java.lang.reflect.Method.invoke(Method.java:525)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    02-17 15:40:20.571: E/AndroidRuntime(1677): at dalvik.system.NativeStart.main(Native Method)

    Can you please help me.
    Thanks again.

    ReplyDelete
  3. […] 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. […]

    ReplyDelete

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...