Quantcast
Channel: niravmehtablog
Viewing all articles
Browse latest Browse all 10

Calling Web Services in Android

$
0
0

Hello friends in today toturial we learn about one common things that required in all our android application- that is web services.
We have to learn about how to call api and fetch data and set to the ui from the different web-services.

In First Tutorial we learn two types 1) Get 2) Post – data encoded

First one 1) GET Method

Mostly execute these task in Async class, Main benefits of it is that it work in backgrounds and in rare load.

Require Execute like following :

We pass two parameter now : user_id and name

getAndsetMyData().execute(“yourURL”+”/user_id/”+userId+”/name/”+name);

public class getAndsetMyData extends AsyncTask<String, Void, String> {
ProgressDialog pd;

@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(AppSettingNotiActivity.this);
pd.setMessage(Html.fromHtml(“<b>Please Wait</b><br/>loading…”));
pd.setIndeterminate(false);
pd.setCancelable(false);
pd.show();
}

@Override
protected String doInBackground(String… params) {
return new DownloadAdapter(Activity.this)
.getJSONData(params[0]);
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.cancel();
try {
JSONObject obj = new JSONObject(result);
Log.v(“dd”, result);
if (obj.getString(“status”).equals(“success”)) {
Toast.makeText(getApplicationContext(),
obj.getString(“response”), Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(),
obj.getString(“response”), Toast.LENGTH_SHORT)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

DownloadAdapter Class :

package com.twc.webservice;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.CursorJoiner.Result;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class DownloadAdapter extends AsyncTask<String, Void, String>{

Context context;
ProgressDialog pr;
public DownloadAdapter(Context c)
{
Context context;
}
public String getJSONData(String url)
{
InputStream is;
StringBuilder strBuilder=new StringBuilder();
HttpClient client=new DefaultHttpClient();
try {

HttpGet httpGet=new HttpGet(url);
HttpResponse res=client.execute(httpGet);
StatusLine sLine=res.getStatusLine();
int resCode=sLine.getStatusCode();

if(resCode==200)
{
HttpEntity entity=res.getEntity();
is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String data;

while((data=br.readLine()) != null)
{
strBuilder.append(data);
}
}

}
catch (Exception e) {
Log.v(“mye”, “getJsonData “+e.toString());

}
return strBuilder.toString();
}

private InputStream openHTTPCon(String url)
{
InputStream is=null;
URLConnection con;
int response=-1;
try {
con = new URL(url).openConnection();
HttpURLConnection httpCon=(HttpURLConnection)con;
httpCon.setAllowUserInteraction(false);
httpCon.setInstanceFollowRedirects(true);
httpCon.setRequestMethod(“GET”);
httpCon.connect();
response=httpCon.getResponseCode();
Log.v(“mye”, “test”);
if(response == HttpURLConnection.HTTP_OK)
{
is=httpCon.getInputStream();
Log.v(“mye”, is.toString());
}

}
catch (Exception e) {
Log.v(“mye”, “openCon “+e.toString());
}
return is;

}

public Bitmap downloadImage(String url)
{
Bitmap bitmap=null;
InputStream is=null;

try
{
is=openHTTPCon(url);
bitmap=BitmapFactory.decodeStream(is);
}
catch (Exception e) {
Log.v(“mye”, “openCon “+e.toString());
}
return bitmap;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pr=new ProgressDialog(context);
pr.show();
}
@Override
protected String doInBackground(String… params) {
getJSONData(params[0]);
return “true”;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals(“true”))
{
pr.cancel();
}
else
{
pr.cancel();
Toast.makeText(context, “Some errore occured!”, Toast.LENGTH_SHORT).show();
}
}
}

Second Way 2) Post Data

Call : getAndsetMyData().execute();

class getAndsetMyData extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
private String msg;

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(Att_Active_Client_Desc.this);
pDialog.setMessage(Html.fromHtml(“<b>Please Wait</b><br/>loading…”));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected String doInBackground(String… params) {
// TODO Auto-generated method stub

JSONObject jsonObjSend = new JSONObject();

try {
jsonObjSend.put(“user_id”, user_id);
jsonObjSend.put(“name”, name);

JSONObject jsonObjRecv = HttpClientJSON.SendHttpPost(“yourURL”, jsonObjSend);
Log.d(“msg”, “—-” + jsonObjRecv.toString());

return “yes”;
} catch (JSONException je) {
je.printStackTrace();
return “fail”;
} catch (Exception e) {
e.printStackTrace();
return “fail”;
}

}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

}

}

HttpclientJson class :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class HttpClientJSON {
private static final String TAG = “HttpClientJSON”;

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);

StringEntity se;
se = new StringEntity(jsonObjSend.toString());
Log.d(“test”, URL);
Log.d(“test”, jsonObjSend.toString());

// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader(“Accept”, “application/json”);
httpPostRequest.setHeader(“Content-type”, “application/json”);
httpPostRequest.setHeader(“Accept-Encoding”, “gzip”); // only set this parameter if you would like to use gzip compression

long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, “HTTPResponse received in [” + (System.currentTimeMillis()-t) + “ms]”);

// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();

if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader(“Content-Encoding”);
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase(“gzip”)) {
instream = new GZIPInputStream(instream);
}

// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(0,resultString.length()); // remove wrapping “[” and “]”

// Transform the String into a JSONObject

Log.d(“test”,resultString);
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,”<JSONObject>\n”+jsonObjRecv.toString()+”\n</JSONObject>”);

return jsonObjRecv;
}

}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
Log.v(“jsonerrore”, e.toString());
}
return null;
}

private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there’s no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*
* (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + “\n”);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

}
Hope its easy and understandable tutorial , in next tutorial we learn about Post enoded data passing and image uploading to server.


Viewing all articles
Browse latest Browse all 10

Trending Articles