RSS

REST clients for Java, MySQL and JSON Restful Web Services

28 Nov

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: ,

3 responses to “REST clients for Java, MySQL and JSON Restful Web Services

  1. christi parks

    December 2, 2012 at 12:48 pm

    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.

     
  2. ipek

    February 18, 2014 at 2:15 am

    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.

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: