Thursday, 6 February 2014

Accessing Rest Web Service through Android!!!

Hello Friends,


In this blog I am going to demonstrate how to use rest web service through android.

Hope this will be useful to you!!!!!
Below is the code for rest web service which returns random value

package com.rest.tutorial;


import java.util.Random;
import javax.ws.rs.GET;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;

import org.json.JSONObject;

@Path("Operations")

public class Operations {
// Getting random Value function
@Path("/getRandomValue")
@GET
@Produces("application/json")
public String getRandomValue() {

JSONObject jsonObject = new JSONObject();

try {
Random rand = new Random();
float START = 1;
float END = 10;
float randomNumber;
if (START > END) {
throw new IllegalArgumentException("Start cannot exceed end");
}
// get the range, casting to long to avoid overflow problems
float range = END - START + 1;
// compute a fraction of the range, 0 <= frac < range
float fraction = (float) (range * rand.nextDouble());
randomNumber = (fraction + START);
jsonObject.put("RandomNumber", String.format("%.2f", randomNumber));
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("value:" + jsonObject.toString());
return jsonObject.toString();
}
}

To access this web service on browser use below url:


Android Code:

i. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.restwebdemo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.restwebdemo.RandomData"
android:label="@string/title_activity_random_data" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

ii.RandomData.java

package com.example.restwebdemo;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.util.UrlUtil;
import com.example.util.WebserviceUtil;

public class RandomData extends Activity implements OnClickListener {
private Button callrestWSButton;
private TextView resultText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.random_data_with_restws);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new    
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
callrestWSButton = (Button) findViewById(R.id.callWSButton);
resultText = (TextView) findViewById(R.id.resultTextView);
callrestWSButton.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.random_data, menu);
return true;
}

/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {

switch (v.getId()) {
case R.id.callWSButton:
// call WS
try {
                               //This is the code for web service invocation
JSONObject jsnobject = WebserviceUtil.getUrlRequest(UrlUtil.getRandomValueurl(), UrlUtil.getRandomValueType());

resultText.setText(jsnobject.getString("RandomNumber").toString());
} catch (Exception ex) {
ex.printStackTrace();
}
break;

default:
break;
}
}
}

Code for WebService Implementation

i.Constants.java

package com.example.util;

public class Constants {

// This is to get mainURL Details
public static final String mainURL = Resource.getMessage("mainURL");
// This is to get randomValueURL Details
public static final String randomValueMethodName= Resource.getMessage("randomValueMethodName");
public static final String randomValueURLMethodType = Resource.getMessage("randomValueURLMethodType");
}

ii.Resouce.java

package com.example.util;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Resource {

private static ResourceBundle resourceBundle = null;

static {
initialize();
}

/**
* Initialize the resource bundle.
* @throws java.lang.RuntimeException
*/
public static void initialize() throws RuntimeException {

try {
resourceBundle = ResourceBundle.getBundle("com.example.util.config");
} catch (MissingResourceException e) {
throw new RuntimeException("no resource bundle found.");
}
}

/**
* This method accept the key as parameter and returns the message for that message from
* properties file.
* @param key
*            key of the property file.
* @return message.
*/
public static String getMessage(String key) {

String message = "";

try {
if (resourceBundle != null) {
message = new String(resourceBundle.getString(key).getBytes("ISO-8859-1"), "UTF-8");
}
} catch (Exception e) {
// message = "** BUNDLE KEY NOT FOUND **";
e.printStackTrace();
}

return message;
}
}

iii)UrlUtil.java
package com.example.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;

public class UrlUtil {

/**
* pradip.kumbhar Sep 24, 2013
*
* @param args
*/

public static StringBuffer getQueryString(HashMap<String, String> params) {

StringBuffer requestParams = new StringBuffer("");

if (params != null) {
Iterator<String> paramIterator = params.keySet().iterator();

while (paramIterator.hasNext()) {

String key = paramIterator.next();
String value = params.get(key);

try {
if (requestParams.length() == 0) {
requestParams = new StringBuffer();
requestParams.append("?");
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(URLEncoder.encode(value, "UTF-8"));
} else {
requestParams.append("&");
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(URLEncoder.encode(value, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
return requestParams;
}

public static String getRandomValueurl() {

String randomValueUrl = null;
// If there are any parameters to web service then you can add it in hasmap and send it as
// parameter to getQueryString() method
randomValueUrl = Constants.mainURL + Constants.randomValueMethodName + getQueryString(null);
return randomValueUrl;
}

public static String getRandomValueType() {

return Constants.randomValueURLMethodType;
}
}

iv) WebserviceUtil.java

package com.example.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

public class WebserviceUtil {

/**
* pradip.kumbhar Sep 16, 2013
*
* @param args
*/
public static void main(String[] args) {

// TODO Auto-generated method stub

}

public static JSONObject getUrlRequest(String serviceurl, String requestMethod) {

HttpURLConnection urlRequest = null;
JSONObject jsnobject = null;
try {
URL url = new URL(serviceurl);
urlRequest = (HttpURLConnection) url.openConnection();
urlRequest.setRequestMethod(requestMethod);
urlRequest.addRequestProperty("Content-Type", "application/json");
urlRequest.addRequestProperty("ACCEPT", "application/json");

InputStream in = new BufferedInputStream(urlRequest.getInputStream());
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
StringBuilder responseString = new StringBuilder();
String line;
// Loop through the buffered input, reading JSON data
while ((line = bufferReader.readLine()) != null) {
responseString.append(line);
}
jsnobject = new JSONObject(responseString.toString());

} catch (Exception e) {
e.printStackTrace();
} finally {
urlRequest.disconnect();
}

return jsnobject;
}
}



2 comments: