Friday, September 14, 2012

Consuming Rest Web-Services in Android | Web Services in Android | Rest Web Services demo in Android


 Dear Friend!
      Its a working demo for consuming rest web service in android try it..


package com.rest.web.services;

import java.io.BufferedReader;
import java.io.InputStreamReader;

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.JSONStringer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class RestWebServicesDemoActivity extends Activity {
       private final static String SERVICE_URI = "http://restwebservice.com/test/Service.svc";

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
       }

       public static void callWebService() {

              try {

                     // make web service connection
                     HttpPost request = new HttpPost(SERVICE_URI + "/TestApplication");
                     request.setHeader("Accept", "application/json");
                     request.setHeader("Content-type", "application/json");
                     // Build JSON string
                     JSONStringer TestApp = new JSONStringer().object().key("id")
                                  .value("1").key("name").value("manish").key("email")
                                  .value("androidhub4you@gmail.com").key("country")
                                  .value("india").endObject();
                     StringEntity entity = new StringEntity(TestApp.toString());

                     Log.d("****Parameter Input****", "Testing:" + TestApp);
                     request.setEntity(entity);
                     // Send request to WCF service
                     DefaultHttpClient httpClient = new DefaultHttpClient();
                     HttpResponse response = httpClient.execute(request);

                     Log.d("WebInvoke", "Saving: " + response.getStatusLine().toString());
                     // Get the status of web service
                     BufferedReader rd = new BufferedReader(new InputStreamReader(
                                  response.getEntity().getContent()));
                     // print status in log
                     String line = "";
                     while ((line = rd.readLine()) != null) {
                           Log.d("****Status Line***", "Webservice: " + line);

                     }

              } catch (Exception e) {
                     e.printStackTrace();
              }

       }

}

21 comments:

  1. Status Line = http/1.0 404 not found
    what to do with this?
    and not getting proper response from server

    ReplyDelete
  2. That mean your server url is wrong..
    Hit on browser it should return code-200

    ReplyDelete
  3. i used this thing with my facebook login application. but now i want to use it with asynctask method. most of the tutorial are confusing. will you upload a sample code which work with asynctask method with web services

    ReplyDelete
    Replies
    1. Hi Just put this code inside do in background in async class, follow my this blog-
      http://www.androidhub4you.com/2013/03/main-thread-issue-in-android-async.html

      Delete
  4. Hello Manish,

    This is Pradeep, Nice tutorial. Thanks for this useful blog. Can you plz upload also the layout codes for your further posts...

    Thnx.

    ReplyDelete
    Replies
    1. Yes sure I will mind it next time..
      But in this post nothing in layout, you can call any layout..

      Delete
  5. Hi Manish I Need Help from u.I am getting HTML Page Response

    I have a URL:http://stressisgone.com/members/users.json

    parameters:
    Registration
    -------------
    email
    first
    last
    zip
    password
    confirm

    Login(same URL)
    -----
    email
    password

    ReplyDelete
    Replies
    1. Problem with your url. I don't think it is .json , it may be .php, .svc, .asp or someting else according which type of service you are using.
      And if it is get service you can test in browser also.
      And you can try combination of "?" With your service url like- xyz.php?name=manish&email=xyz


      Etc...

      Delete
    2. Hi manish can u please tel me how to test this REST based webservies in android. If you have example can u post. Thank you

      Delete
    3. Hi Praaveen!
      Above code for client side(Android) so just right REST full web-services for testing the demo. You can use any language (java, php, .net) for write web-services.

      Delete
  6. Hi Manish,
    What should be the url in this case. I am unable to open the webpage http://localhost:8080/wifidirect.txt. I need to post these details in above webpage. what exactly i am missing?


    public class LongOperation extends AsyncTask {
    protected Void doInBackground(String... urls) {
    Log.d("LongOperation:::","doInBackground mtd") ;
    try {

    HttpClient client = new DefaultHttpClient();
    //Timeout Limit
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
    HttpResponse response;
    JSONObject json = new JSONObject();
    HttpPost post = new HttpPost("http://localhost:8080/wifidirect.txt");
    json.put("email", "ss@gmail.com");
    json.put("password", "22445");
    Log.d("json value::",json.toString());
    StringEntity se = new StringEntity( json.toString());
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(se);
    response = client.execute(post);
    Log.d("client response::: ","after executing response");


    Log.d("samba's Response:::","is not null");

    BufferedReader rd = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent()));
    // print status in log
    String line = "";
    while ((line = rd.readLine()) != null) {
    Log.d("****Status Line***", "Webservice: " + line);

    }




    } catch (JSONException e) {
    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (IOException e) {
    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return null;
    }


    adb logcat output

    D/****Status Line***( 2479): Webservice: The requested resource does not exist on this server.

    ReplyDelete
    Replies
    1. Hi Sam,
      I feel your URL is wrong. in which language you have written your web-service? .txt is not any format I think, its indicate text file. it should be .php, .aspx or any other script language. I think that's why you are getting that issue-
      The requested resource does not exist on this server

      Delete
  7. hi, I take error as -> "The server encountered an error processing the request. See server logs for more details."

    public void excutePost(JSONObject json){
    // make web service connection
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost request = new HttpPost(SERVICE_URI + "/SaveAgent");
    request.setHeader("Accept", "application/json");
    request.setHeader("Content-type", "application/json");

    try {
    entity = new StringEntity(json.toString());
    request.setEntity(entity);
    HttpResponse response = httpClient.execute(request);
    // Get the status of web service
    BufferedReader rd = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent()));
    // print status in log
    String line = "";
    while ((line = rd.readLine()) != null) {
    Log.d("****Status Line***", "Webservice: " + line);

    }
    } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    }

    ReplyDelete
    Replies
    1. your web-service in which language written? .net,php,java ? Basically this is a Rest-full web-service for .net.

      Delete
  8. Hi Manish,
    In my App I have 2 activity I want if the application run first time then activity 1 show but if application already run 1 times then if user launch application then activity 2 is directly open.

    ReplyDelete
    Replies
    1. For this use shared preferences like this-
      1)make variable-
      boolean isFirstTime;
      SharedPreferences app_preferences;

      app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
      isFirstTime = app_preferences.getBoolean("isFirstTime", false);

      2)Now check it for first login-
      if (isFirstTime == false){
      SharedPreferences.Editor editor = app_preferences.edit();
      editor.putBoolean("isFirstTime", true);
      editor.commit();

      Intent intent = new Intent();
      intent.setClass(SplashActivity.this,
      FirstPage.class);
      startActivity(intent);
      }
      else{
      Intent intent = new Intent();
      intent.setClass(SplashActivity.this,
      SecondPage.class);
      startActivity(intent);

      }

      Delete
  9. Hi Manish,
    This is much required for me, Is there any way to like facebook page on button click without redirecting user to facebook page.anyone who have idea about this can reply.

    ReplyDelete
    Replies
    1. With out one time login on Facebook you can't. It is Facebook security policy, ones you have to allow user to do it. You can do one thing force user to login with Facebook account first time and keep his credential in preference for next time use.

      Delete
    2. thanks for reply,

      Login is not issue for me, if user is already login using facebook then how to enable auto like on button click without user interaction with facebook page.

      Delete
  10. Can we call the POST services of wcf with this code.. I coudn't be able to get the response using the POST service call. i am getting the null response? how can i call it?

    ReplyDelete
  11. it really means alot to me .
    thank you

    ReplyDelete