How to send and recieve JSON form and to service REST in android


Server chúng ta thiết lập như sau


@POST
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 @Path("/parameter")
 public Response getParameter(String param){
System.out.println(param);
       Message ms = new Message("true");
       Gson gson = new Gson();
       String value = gson.toJson(ms).toString();
       return Response.ok(value).build();
 }

Phía client (Android app)


@SuppressWarnings("serial")
public class EmailInfo implements Serializable {
      private String rideId;
      private String email;
      public String getRideId() {
           return rideId;
      }
      public void setRideId(String rideId) {
this.rideId = rideId;
}
 public String getEmail() {
 return email;
 }
 public void setEmail(String email) {
 this.email = email;
 }
 public EmailInfo(String rideId, String email) {
 this.rideId = rideId;
 this.email = email;
 }
 public EmailInfo() {
 super();
 }

}

Main in android

</pre>
 String url = "http://192.168.0.102:8080/RESTService/REST/service/parameter";
 try {
 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost post = new HttpPost(url);
 Gson gson = new Gson();
 Log.v("RideEmailJson",gson.toJson(new EmailInfo("id001", "thaihoanghai@gmail.com")).toString());
 StringEntity se = new StringEntity(gson.toJson(new EmailInfo("id001", "thaihoanghai@gmail.com")).toString());
 se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
 post.setEntity(se);
 HttpResponse httpRespone = httpClient.execute(post);
 HttpEntity httpEntity = httpRespone.getEntity();
 InputStream is = httpEntity.getContent();
 BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
 sb.append(line + "\n");
 }
 is.close();
 String value = sb.toString();
 Toast.makeText(this, value, Toast.LENGTH_LONG).show();
 } catch(Exception e) {
 e.printStackTrace();
 Log.v("Error", "Cannot Estabilish Connection");
 }
 }
<pre>

Class JSONParser.java Send and Recieve with HTTPGET and POST

</pre>
package com.example.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
 static InputStream is = null;
 static JSONObject jObj = null;
 static JSONArray jArray = null;
 static String json = "";

public JSONParser() {

}
 /**
 * makeHttpRequestJSONObject is receive JSONObject from to server by URL
 * @param url : URL from service
 * @param method : HttpGET or HttpPOST
 * @param params : List parameters is send to server
 * @return : JSONOject
 */
 public JSONObject makeHttpRequestJSONObject(String url, String method, List<NameValuePair> params){
 // Making Http request
 try{
 // check for request method
 if(method == "POST"){
 // request method is POST
 // defaultHttpClient
 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(url);
 httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpRespone = httpClient.execute(httpPost);
 HttpEntity httpEntity = httpRespone.getEntity();
 is = httpEntity.getContent();
 }else if(method == "GET"){
 // request method is GET
 DefaultHttpClient httpClient = new DefaultHttpClient();
 String paramString = URLEncodedUtils.format(params, "utf-8");
 url += "?" + paramString;
 HttpGet httpGet = new HttpGet(url);
 httpGet.addHeader("accept", "application/json");

HttpResponse httpResponse = httpClient.execute(httpGet);
 HttpEntity httpEntity = httpResponse.getEntity();
 is = httpEntity.getContent();
 }
 }catch (UnsupportedEncodingException e) {
 e.printStackTrace();
 } catch (ClientProtocolException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 try {
 BufferedReader reader = new BufferedReader(new InputStreamReader(
 is, "iso-8859-1"), 8);
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
 sb.append(line + "\n");
 }
 is.close();
 json = sb.toString();
 } catch (Exception e) {
 Log.e("Buffer Error", "Error converting result " + e.toString());
 }

// try parse the string to a JSON object
 try {
 jObj = new JSONObject(json);
 } catch (JSONException e) {
 Log.e("JSON Parser", "Error parsing data " + e.toString());
 }

// return JSON String
 return jObj;
 }

/**
 * makeHttpRequestJSONArray is receive JSONArray from to server by URL
 * @param url : URL from service
 * @param method : HttpGET or HttpPOST
 * @param params : List parameters is send to server
 * @return : JSONArray . Array of JSObject
 */
 public JSONArray makeHttpRequestJSONArray(String url, String method, List<NameValuePair> params){
 // Making Http request
 try{
 // check for request method
 if(method == "POST"){
 // request method is POST
 // defaultHttpClient
 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(url);
 httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpRespone = httpClient.execute(httpPost);
 HttpEntity httpEntity = httpRespone.getEntity();
 is = httpEntity.getContent();
 }else if(method == "GET"){
 // request method is GET
 DefaultHttpClient httpClient = new DefaultHttpClient();
 String paramString = URLEncodedUtils.format(params, "utf-8");
 url += "?" + paramString;
 HttpGet httpGet = new HttpGet(url);
 httpGet.addHeader("accept", "application/json");

HttpResponse httpResponse = httpClient.execute(httpGet);
 HttpEntity httpEntity = httpResponse.getEntity();
 is = httpEntity.getContent();
 }
 }catch (UnsupportedEncodingException e) {
 e.printStackTrace();
 } catch (ClientProtocolException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 try {
 BufferedReader reader = new BufferedReader(new InputStreamReader(
 is, "iso-8859-1"), 8);
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
 sb.append(line + "\n");
 }
 is.close();
 json = sb.toString();
 } catch (Exception e) {
 Log.e("Buffer Error", "Error converting result " + e.toString());
 }

// try parse the string to a JSON object
 try {
 jArray = new JSONArray(json);
 } catch (JSONException e) {
 Log.e("JSON Parser", "Error parsing data " + e.toString());
 }

// return JSON String
 return jArray;
 }

/**
 * makeHttpRequestJSONArray is send and receive JSONObject from to server by URL
 * @param url : URL from service
 * @param obj : JSONObject
 * @return JSONObject
 */
 public JSONObject makeHttpRequestJSONObject(String url, JSONObject obj){
 // Making Http request
 try {
 // request method is POST
 // defaultHttpClient
 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(url);
 StringEntity se = new StringEntity(obj.toString());
 //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
 httpPost.setHeader("Accept", "application/json");
 httpPost.setHeader("Content-type", "application/json");
 httpPost.setEntity(se);
 HttpResponse httpRespone = httpClient.execute(httpPost);
 HttpEntity httpEntity = httpRespone.getEntity();
 is = httpEntity.getContent();
 } catch (IOException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 try {
 BufferedReader reader = new BufferedReader(new InputStreamReader(
 is, "iso-8859-1"), 8);
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
 sb.append(line + "\n");
 }
 is.close();
 json = sb.toString();
 } catch (Exception e) {
 Log.e("Buffer Error", "Error converting result " + e.toString());
 }

// try parse the string to a JSON object
 try {
 jObj = new JSONObject(json);
 } catch (JSONException e) {
 Log.e("JSON Parser", "Error parsing data " + e.toString());
 }

// return JSON String
 return jObj;
 }

&nbsp;

}
<pre>

Server của chúng ta :

</pre>
package webService;

import java.util.List;

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

import com.google.gson.Gson;

import dao.PersonUtils;
import dto.Message;
import dto.Person;

@Path("/PersonService")
public class PersonService {
 @GET
 @Path("/GetPersons")
 @Produces(MediaType.APPLICATION_JSON)
 public String getPersons(){
 // url : http://localhost:8080/WS-Mobile/REST/PersonService/GetPersons
 String value = "";
 try {
 List<Person> listPerson = PersonUtils.getPersons();
 Gson gson = new Gson();
 value = gson.toJson(listPerson);
 } catch (Exception e) {e.printStackTrace();}
 return value;
 }
 @GET
 @Path("/GetPerson/{id}")
 @Produces(MediaType.APPLICATION_JSON)
 public String getPersonWithID(@PathParam("id") String id){
 // url : http://localhost:8080/WS-Mobile/REST/PersonService/GetPerson/{id}
 // return 1 : id in valid
 // return Person : ok
 // return false : not ok
 Person p = PersonUtils.getPersonWithID(id);
 Gson gson = new Gson();
 try {
 Integer.parseInt(id);
 } catch (NumberFormatException e) {return gson.toJson(new Message("1"));}
 if(p != null)
 return gson.toJson(p).toString();
 return gson.toJson(new Message("false")).toString();
 }


 @GET
 @Path("/SearchPerson/{name}")
 @Produces(MediaType.APPLICATION_JSON)
 public String searchPersonWithName(@PathParam("name") String name){
 // url : http://localhost:8080/WS-Mobile/REST/PersonService/SearchPerson/{name}
 // return 1 : id in valid
 // return Person : ok
 // return false : not ok
 List<Person> listPerson = PersonUtils.searchPersonWithName(name);
 Gson gson = new Gson();
 return gson.toJson(listPerson).toString();

 }

 @GET
 @Path("/InsertPerson")
 public String addPerson(@QueryParam("iname") String name,@QueryParam("ibirthday") String birthday,@QueryParam("iaddress") String address){
 //http://localhost:8080/WS-Mobile/REST/PersonService/InsertPerson?iname=?&ibirthday=?&iaddress=?
 Gson gson = new Gson();
 Person p = new Person(null, name, address, birthday);
 if(PersonUtils.addPerson(p))
 return gson.toJson(new Message("true"));
 return gson.toJson(new Message("false"));
 }


 @GET
 @Path("/UpdatePerson")
 public String updatePerson(@QueryParam("uid") String id,
 @QueryParam("uname") String name,
 @QueryParam("ubirthday") String birthday,
 @QueryParam("uaddress") String address){
 //http://localhost:8080/WS-Mobile/REST/PersonService/InsertPerson?uid=?&uname=?&uaddress=?&ubirthday=?
 Gson gson = new Gson();
 Person p = new Person(id, name, address, birthday);
 if(PersonUtils.updatePerson(p))
 return gson.toJson(new Message("true"));
 return gson.toJson(new Message("false"));
 }




}
<pre>

Thao tác với Server Client :

</pre>
String url = "http://192.168.0.102:8080/WS-Mobile/REST/PersonService/GetPersons";
 List<NameValuePair> params = new ArrayList<NameValuePair>();
 JSONArray array = new JSONParser().makeHttpRequestJSONArray(url, "GET", params);
 try {

 Toast.makeText(this,array.length() + " ", Toast.LENGTH_LONG).show();
 } catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

String url2 = "http://192.168.0.102:8080/WS-Mobile/REST/PersonService/GetPerson/1";
 JSONObject obj = new JSONParser().makeHttpRequestJSONObject(url2, "GET", params);
 try {
 Toast.makeText(this, obj.getString("name") + " ", 4000).show();
 } catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 String url3 = "http://192.168.0.102:8080/WS-Mobile/REST/PersonService/SearchPerson/ky";
 url3 = url3.replace(" ", "%20");
 JSONArray obj2 = new JSONParser().makeHttpRequestJSONArray(url3, "GET", params);
 if(obj2.length() <= 0)
 Toast.makeText(this,"not found" + " ", 4000).show();

try {
 Toast.makeText(this, obj2.getJSONObject(0).getString("address") + " ", 4000).show();
 } catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 String url4 = "http://192.168.0.102:8080/WS-Mobile/REST/PersonService/InsertPerson";
 NewPairValue param1 = new NewPairValue("iname", "Tran thi thu thuy");
 NewPairValue param2 = new NewPairValue("iaddress", "So 126 Duong So 1 TN P.16 GV");
 NewPairValue param3 = new NewPairValue("ibirthday", "18/5/1992 2:30 AM");
 params.add(param1);
 params.add(param2);
 params.add(param3);
 JSONObject result = new JSONParser().makeHttpRequestJSONObject(url4, "GET", params);
 try {
 if(result.getString("result").equalsIgnoreCase("true"))
 Toast.makeText(this, "Insert Success", Toast.LENGTH_LONG).show();
 else
 Toast.makeText(this, "Insert Fail", Toast.LENGTH_LONG).show();
 } catch (JSONException e) {
 e.printStackTrace();
 }
 String url5 = "http://192.168.0.102:8080/WS-Mobile/REST/PersonService/UpdatePerson";
 NewPairValue param00 = new NewPairValue("uid", "28");
 NewPairValue param11 = new NewPairValue("uname", "Tran thi thu thuaaaay");
 NewPairValue param22 = new NewPairValue("uaddress", "So 126 Duong So 1 TN P.16 GV");
 NewPairValue param33 = new NewPairValue("ubirthday", "18/5/1992 2:30 AM");
 params.add(param00);
 params.add(param11);
 params.add(param22);
 params.add(param33);
 JSONObject result1 = new JSONParser().makeHttpRequestJSONObject(url5, "GET", params);
 try {
 if(result1.getString("result").equalsIgnoreCase("true"))
 Toast.makeText(this, "Insert Success", Toast.LENGTH_LONG).show();
 else
 Toast.makeText(this, "Insert Fail", Toast.LENGTH_LONG).show();
 } catch (JSONException e) {
 e.printStackTrace();
 }

try {
 String url6 = "http://192.168.0.102:8080/RESTService/REST/service/parameter";
 EmailInfo email = new EmailInfo("id1010", "kupjkupj@yahoo.com");
 JSONObject obj1 = new JSONObject(new Gson().toJson(email));
 obj1 = new JSONParser().makeHttpRequestJSONObject(url6, obj1);
 Toast.makeText(this, obj1.toString(), Toast.LENGTH_LONG).show();
 } catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
<pre>

 

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: