4

How to send and receive JSON data Android and ASP.Net MVC ? I have an Android Login application, which has a Login activity class and a JSONParser class. Using the JSONParser class, I am passing the url of the mvc location, "POST" parameter and my parameters username, password as json to MVC. I have an ASP.net mvc code that accepts the username and password, and if a match is found, it will return json data as "username" : "admin, "success" : 1.

The code for Login Activity class is:

protected String doInBackground(String... arg0) {
    // TODO Auto-generated method stub

    new Thread() {          
        // Running Thread.
        public void run() {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("userid", username.getText().toString().trim()));
            params.add(new BasicNameValuePair("password", password.getText().toString().trim()));

            JSONObject json = jsonParser.makeHttpRequest("http://localhost:8012/Login/Login","GET", params);
            Log.d("Create Response", json.toString());
            try {
                    int success = json.getInt("success");
                    if (success == 1) {

                        Intent newregistrationIntent = new Intent(MainActivity.this,mydashActivity.class);
                        startActivityForResult(newregistrationIntent, 0);
                    } 
                    else 
                    {
                                i=1;
                                flag=1;
                    }
                } catch (JSONException e) {
                            e.printStackTrace();
                }
        }
    }.start();


    return null;




}

The code for JSONParser is :

    public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(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));


                httpPost.setHeader("Content-type", "application/json");





                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.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);

                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;

    }
}

My ASP.Net MVC code is :

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using System.Web.Script.Serialization;

namespace MvcApplication1.Controllers
{
    public class LoginController : Controller
    {
        Dictionary<string, object> loginParam = new Dictionary<string, object>();
        //
        // GET: /Login/

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(Login cs)
        {
            return Json(new { username="admin", success = 1 });

        }

        [HttpGet]
        public ActionResult Profile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Profile(Login cs)
        {
            return View("");
        }


    }
}

I am not sure whether actually a connection is made from android to the mvc code. I am also not sure whether the MVC controller is hit at the Login () by the android code. How to make sure, the JSON data is send from Android, as well as the data is returned from MVC code ?

Note: I am not actually comparing the data in MVC code. I am just returning the data. This is my first MVC code.

Roshan
  • 497
  • 1
  • 6
  • 16
  • two possibilitie: 1.you will fetch all the records from server and compare the login data with that for authentication 2/you will send username and passwrord to server and compare the data at server and return boolean true if valid..or return false if not valid// which aproach you are trying? – Wasim Ahmed Jun 12 '14 at 06:15
  • I am just trying...so, the data that is passed from Android is not important. Just the action that happens and whether the result returns is what that matters. Actually, I need to send the username and password to the server, compare it there, and return back a success message, let it be boolean true/false, or an integer value. What I am trying here is to return back an integer value. – Roshan Jun 12 '14 at 06:22
  • Hope This link will help you. http://stackoverflow.com/questions/11014953/asp-net-web-api-authentication – Wasim Ahmed Jun 12 '14 at 06:27
  • That didnt helped me much. – Roshan Jun 12 '14 at 06:43

1 Answers1

0

because of you used "Get" method :

JSONObject json = jsonParser.makeHttpRequest("http://localhost:8012/Login/Login","GET", params);

While the login method is [httpPost]

[HttpPost] public ActionResult Login(Login cs) { return Json(new { username="admin", success = 1 });

}

ABlue
  • 664
  • 6
  • 20