JSON Web Services for Android

flosssnailsMobile - Wireless

Dec 10, 2013 (3 years and 8 months ago)

76 views

Thursday, 4 November 2010

1


JSON Web Services for Android

Author: Bernard O’Leary

Contents

The basics
................................
................................
................................
................................
..........

1

JSON and JSON web services for practice

................................
................................
...........................

1

Raw JSON:

................................
................................
................................
................................
.....

2

Indented:
................................
................................
................................
................................
.......

2

Translated into Java:

................................
................................
................................
......................

2

Getting your app to talk HTTP and JSON

................................
................................
............................

3

WebService class

................................
................................
................................
...........................

3

GSON
................................
................................
................................
................................
.............

6

User interface
................................
................................
................................
................................
....

6

Security

................................
................................
................................
................................
.............

7

Putting it all together
................................
................................
................................
.........................

8

Fur
ther details

................................
................................
................................
................................
...

9


T
h
e

b
a
s
i
c
s


I
D
E
:

e
c
l
i
p
s
e

U
I

d
e
s
i
g
n
e
r
:

d
r
o
i
d
d
r
a
w

A
n
d
r
o
i
d

l
i
b
r
a
r
i
e
s
:

http://developer.android.com/resources/tutorials/hello
-
world.html

J
S
O
N

a
n
d

J
S
O
N

w
e
b

s
e
r
v
i
c
e
s

f
o
r

p
r
a
c
t
i
c
e


(JavaScript Object Notation)

is a lightweight data
-
interchange format
.



http://www.json.org/



P
i
c
k
e
d

J
S
O
N

b
e
c
au
se

I

w
as

o
ri
gi
na
ll
y
d
o
i
n
g

t
h
e

s
a
m
e

t
h
i
n
g

w
i
t
h

J
2
M
E

a
n
d

i
t

w
a
s

a

n
a
t
u
r
a
l

t
r
a
n
s
i
t
i
o
n
.

S
o
m
e

J
S
O
N

w
e
b

s
e
r
v
i
c
e

e
x
a
m
p
l
e
s
:



http://www.geonames.org/export/JSON
-
webservices.html

http://ws.geonames.org/earthquakesJSON?north=44.1&south=
-
9.9&east=
-
22.4&west=55.2




Thursday, 4 November 2010

2


R
a
w

J
S
O
N
:


{"earthquakes":[{"eqid":"2007hear","magnitude":8.4,"lng":101.3815,"src":"us","datet
ime":"2007
-
09
-
12 09:10:26","depth":30,"lat":
-
4.5172},{"eqid":"2007aqbk"
,"magnitude":8,"lng":156.9567,"src":"us","datetime":"2007
-
04
-
01 18:39:56","depth":10,"lat":
-
8.4528},{"eqid":"2007hec6","magnitude":7.8,"lng":100.9638,"src":"us","datetime":"20
07
-
09
-
12 21:49:01","depth":10,"lat":
-
2.5265},{"eqid":"a00043nx","magnitude":7.7,"
lng":100.1139,"src":"us","datetime":"20
10
-
10
-
25 12:42:22","depth":20.6,"lat":
-
3.4841},{"eqid":"2010utc5","magnitude":7.7,"lng":97.1315,"src":"us","datetime":"201
0
-
04
-
06
20:15:02","depth":31,"lat":2.3602},{"eqid":"2009mebz","magnitude":7.6,"lng":99.9606
,"sr
c":"us","datetime":"2009
-
09
-
30 08:16:09","depth":80,"lat":
-
0.7889},{"eqid":"2009kdb2","magnitude":7.6,"lng":92.9226,"src":"us","datetime":"200
9
-
08
-
10
17:55:39","depth":33.1,"lat":14.0129},{"eqid":"2010zbca","magnitude":7.6,"lng":123.
533,"src":"us","datetim
e":"2010
-
07
-
23
20:51:11","depth":576.3,"lat":6.4939},{"eqid":"2010xkbv","magnitude":7.5,"lng":91.9
379,"src":"us","datetime":"2010
-
06
-
12
17:26:50","depth":35,"lat":7.7477},{"eqid":"2007fubd","magnitude":7.5,"lng":107.655
3,"src":"us","datetime":"2007
-
08
-
08 1
5:04:58","depth":289.2,"lat":
-
5.9682}]}


I
n
d
e
n
t
e
d
:


{"earthquakes":

[


{



"eqid":"2007hear"



,"magnitude":8.4



,"lng":101.3815



,"src":"us"



,"datetime":"2007
-
09
-
12 09:10:26"



,"depth":30



,"lat":
-
4.5172


}


,{





}

]

}


T
r
a
n
s
l
a
t
e
d

i
n
t
o

J
a
v
a
:


package com.infostructure.experimental;


public class Earthquake {



public String eqid;


public String src;


public String datetime;


public double magnitude;


public double lng;


public double lat;


public double depth;



@Override


public String toString()


{



return "eqid: "+alertid+ " src:
"+aler
ttext+ " datetime: "+alertdate;

Thursday, 4 November 2010

3



}

}

G
e
t
t
i
n
g

y
o
u
r

a
p
p

t
o

t
a
l
k

H
T
T
P

a
n
d

J
S
O
N


Shamelessly

b
o
r
r
o
w
e
d

s
o
m
e

c
o
d
e

f
r
o
m


J
o
s
e

C

G
o
m
e
z

:



htt
p://www.josecgomez.com/2010/04/30/android
-
accessing
-
restfull
-
web
-
services
-
using
-
json/



W
e
b
S
e
r
v
i
c
e

c
l
a
s
s



package com.infostructure.experimental;


import java.io.IOException;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net
.URLConnection;

import java.net.URLEncoder;

import java.util.Map;


import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.methods.HttpPut;

import org.apache.http.client.methods.HttpDelete;

import org.apache.http.client.params.ClientPNames;

import org.apache.http.client.params.CookiePolicy;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import

org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.apache.http.protocol.BasicHttpContext;

import org.apache.http.protocol.HttpContext;

import org.apache.http.uti
l.EntityUtils;

import org.json.JSONException;

import org.json.JSONObject;


import android.util.Log;


import com.google.gson.Gson;


public class WebService{



DefaultHttpClient httpClient;


HttpContext localContext;


private String ret;



HttpResponse response = null;


HttpPost httpPost = null;


HttpGet httpGet = null;


HttpPut httpPut = null;


HttpDelete httpDelete = null;


String webServiceUrl;



//The serviceName should be the name of the Service you are going to be

using.

Thursday, 4 November 2010

4



public WebService(String serviceName){


HttpParams myParams = new BasicHttpParams();



HttpConnectionParams.setConnectionTimeout(myParams, 10000);


HttpConnectionParams.setSoTimeout(myParams, 10000);


httpClient = ne
w DefaultHttpClient(myParams);


localContext = new BasicHttpContext();


webServiceUrl = serviceName;



}



//Use this method to do a HttpPost
\
WebInvoke on a Web Service


public String webInvoke(String methodName, Map<String, Object>
params) {




JSONObject jsonObject = new JSONObject();




for (Map.Entry<String, Object> param : params.entrySet()){




try {





jsonObject.put(param.getKey(), param.getValue());




}




catch (JSONException e) {





Log.e("Groshie", "JSONException : "+e);




}



}


return webInvoke(methodName, jsonObject.toString(), "application/json");


}



// POST


private String webInvoke(String methodName, String data, String contentType) {


ret =

null;



httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.RFC_2109);



httpPost = new HttpPost(webServiceUrl + methodName);


response = null;



StringEntity tmp = null;



//httpPost.set
Header("User
-
Agent", "SET YOUR USER AGENT STRING HERE");


httpPost.setHeader("Accept",
"text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,i
mage/png,*/*;q=0.5");



if (contentType != null) {


httpPost.
setHeader("Content
-
Type", contentType);


} else {


httpPost.setHeader("Content
-
Type", "application/x
-
www
-
form
-
urlencoded");


}



try {


tmp = new StringEntity(data,"UTF
-
8");


} catch (UnsupportedEncodingExc
eption e) {


Log.e("Groshie", "HttpUtils : UnsupportedEncodingException : "+e);


}



httpPost.setEntity(tmp);



Log.d("Groshie", webServiceUrl + "?" + data);



try {


response = httpClient.execute(httpPost,localContext);



if (response != null) {


ret = EntityUtils.toString(response.getEntity());


}


} catch (Exception e) {

Thursday, 4 November 2010

5



Log.e("Groshie", "HttpUtils:
" + e);


}



return ret;


}



// GET


//Use this method to do a HttpGet/WebGet on the web service


public String webGet(String methodName, Map<String, String> params) {



String getUrl = webServiceUrl + methodName;




int i
= 0;



for (Map.Entry<String, String> param : params.entrySet())



{




if(i == 0){





getUrl += "?";




}




else{





getUrl += "&";




}





try {





getUrl += param.getKey() + "=" +
URLEncoder.encode(param.getValue(),"UTF
-
8");




} catch (UnsupportedEncodingException e) {





// TODO Auto
-
generated catch block





e.printStackTrace();




}





i++;



}



httpGet = new HttpGet(getUrl);


Log.e("WebGetURL: ",getUrl);



try {


response = httpClient.execute(httpGet);


} catch (Exception e) {


Log.e("Groshie:", e.getMessage());


}



// we assume that the response body contains the error

message


try {


ret = EntityUtils.toString(response.getEntity());


} catch (IOException e) {


Log.e("Groshie:", e.getMessage());


}



return ret;


}



public static JSONObject Object(Object o){



try {




return new JSONObject(new Gson().toJson(o));



} catch (JSONException e) {




e.printStackTrace();



}



return null;


}



public InputStream getHttpStream(String urlString) throws IOException {


InputStream in = null;


in
t response =
-
1;



URL url = new URL(urlString);


URLConnection conn = url.openConnection();



if (!(conn instanceof HttpURLConnection))

Thursday, 4 November 2010

6



throw new IOException("Not an HTTP connection");



try{


HttpURLConn
ection httpConn = (HttpURLConnection) conn;


httpConn.setAllowUserInteraction(false);


httpConn.setInstanceFollowRedirects(true);


httpConn.setRequestMethod("GET");


httpConn.connect();



response = httpConn.getResponseCode();



if (response == HttpURLConnection.HTTP_OK) {


in = httpConn.getInputStream();


}


} catch (Exception e) {


throw new IOException("E
rror connecting");


} // end try
-
catch



return in;


}



public void clearCookies() {


httpClient.getCookieStore().clear();


}



public void abort() {


try {


if (httpClient != null) {


Syst
em.out.println("Abort.");


httpPost.abort();


}


} catch (Exception e) {


System.out.println("Your App Name Here" + e);


}


}

}



G
S
O
N


I
n

o
r
d
e
r

t
o

g
e
t

t
h
i
s

c
l
a
s
s

t
o

c
o
m
p
i
l
e
,

n
e
e
d

t
o

g
e
t

t
h
e

G
S
O
N

l
i
b
r
a
r
y
:



http://code.google.com/p/google
-
gson/


A Java library to convert JSON to Java objects and vice
-
v
ersa





a
n
d

a
d
d

t
o

y
o
u
r

p
r
o
j
e
c
t

s

b
u
i
l
d

p
a
t
h
.

U
s
e
r

i
n
t
e
r
f
a
c
e


U
s
e

d
r
o
i
d
d
r
a
w

t
o

p
u
t

a

b
a
s
i
c

U
I

t
o
g
e
t
h
e
r
:



<?xml
version="1.0" encoding="utf
-
8"?>

<AbsoluteLayout

android:id="@+id/widget0"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

Thursday, 4 November 2010

7


xmlns:android="http://schemas.android.com/apk/res/android"
>

<Button

android:id="@+id/btninvokeWebService"

and
roid:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Invoke Web Service"

android:layout_x="10px"

android:layout_y="10px"
>

</Button>

</AbsoluteLayout>



L
o
o
k
s

l
i
k
e

t
h
i
s
:






P
u
t

t
h
e

g
e
n
e
r
a
t
e
d

X
M
L

c
o
d
e

i
n
t
o


<
Y
O
U
R
_
P
R
O
J
E
C
T
_
N
A
M
E
>
\
res
\
layout
\
m
a
i
n
.
x
m
l

.

S
e
c
u
r
i
t
y


T
o

g
e
t

A
n
d
r
o
i
d

t
o

a
l
l
o
w

i
n
t
e
r
n
e
t

a
c
c
e
s
s
,

e
d
i
t

t
h
e

Android

p
r
o
j
e
c
t

s


AndroidMainfest.xml


f
i
l
e
:



<manifest

xlmns:android
...
>


...


<uses
-
permission

android:name
=
"android.permission.INTERNET"
>

Thursday, 4 November 2010

8



</uses
-
permission>

</manifest>


P
u
t
t
i
n
g

i
t

a
l
l

t
o
g
e
t
h
e
r


A

s
i
m
p
l
e

f
r
o
n
t
-
e
n
d

t
h
a
t

u
s
e
s

t
h
e


W
e
b
S
e
r
v
i
c
e


a
n
d


E
a
r
t
h
q
u
a
k
e


c
l
a
s
s
e
s
,

t
h
e

d
r
o
i
d
d
r
a
w

U
I

o
u
t
p
u
t

a
n
d

b
y

i
m
p
l
i
c
a
t
i
o
n
,

t
h
e

G
S
O
N

l
i
b
r
a
r
y
:



package com.infostructure.experimental;


import java.lang.reflect.Type;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;


import android.app.Activity;

import android.os.Bundle;


import android.widget.EditText;

import android.widget.Te
xtView;

import android.widget.Button;

import android.util.Log;

import android.view.View;


public class MainActivity extends Activity

{


private Button btninvokeWebService;



/** Called when the activity is first created. */


@Override


public void onCreate(Bundle savedInstanceState)


{



super.onCreate(savedInstanceState);



setCont
entView(R.layout.main);



initControls();


}



private void initControls()


{



btninvokeWebService.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ invokeWebService(); }});


}



private void invokeWebService()


{



// Instan
tiate the Web Service Class with he URL of the web service
not that you must pass



WebService webService = new
WebService("http://ws.geonames.org/earthquakesJSON");




//Pass the parameters if needed



Map<String, String> params = new HashMap<String, String>();



params.put("north", "44.1");



params.put("south", "
-
9.9");



params.put("east", "
-
22.4");



params.put("west", "55.2");




//Get JSON response from server the "" are where the method name wou
ld
normally go if needed example

Thursday, 4 November 2010

9




String response = webService.webGet("", params);




try



{




//Parse Response into our object




Type collectionType = new
TypeToken<List<Earthquake>>(){}.getType();




List<
Earthquake
>
q
u
a
k
e
s

= new Gson().fromJson(response,
collectionType);



}



catch(Exception e)



{




Log.d("Error: ", e.getMessage());



}


}

}


Further details


http://bernard
-
on
-
technology.blogspot.com/2010/10/programm
ing
-
droid.html