简体   繁体   English

如何在Android和ASP.net MVC之间发送和接收JSON

[英]How to send and receive JSON between Android and ASP.net mvc

How to send and receive JSON data Android and ASP.Net MVC ? 如何在Android和ASP.Net MVC中发送和接收JSON数据? I have an Android Login application, which has a Login activity class and a JSONParser class. 我有一个Android Login应用程序,它具有Login活动类和JSONParser类。 Using the JSONParser class, I am passing the url of the mvc location, "POST" parameter and my parameters username, password as json to MVC. 使用JSONParser类,我将mvc位置的URL,“ POST”参数和我的参数用户名,密码(作为json)传递给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. 我有一个接受用户名和密码的ASP.net mvc代码,如果找到匹配项,它将以“用户名”:“ admin”,“成功”:1返回json数据。

The code for Login Activity class is: Login Activity类的代码是:

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 : JSONParser的代码是:

    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 : 我的ASP.Net MVC代码是:

    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. 我不确定实际上是否从android到mvc代码建立了连接。 I am also not sure whether the MVC controller is hit at the Login () by the android code. 我也不确定Android代码是否在Login()上击中了MVC控制器。 How to make sure, the JSON data is send from Android, as well as the data is returned from MVC code ? 如何确保JSON数据是从Android发送的,以及数据是从MVC代码返回的?

Note: I am not actually comparing the data in MVC code. 注意:我实际上不是在比较MVC代码中的数据。 I am just returning the data. 我只是返回数据。 This is my first MVC code. 这是我的第一个MVC代码。

 public static String POST( String username,String password){
    String url=Constants.url_registration;
    InputStream inputStream = null;
    String result = "";
    try {
        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);
        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("username", username);
        jsonObject.accumulate("password", password);


        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);
        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

because of you used "Get" method : 因为您使用了“获取”方法:

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

While the login method is [httpPost] 登录方法为[httpPost]

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过调用Web服务在asp.net和android之间发送和接收数据 - How to send and receive data in between asp.net & android by calling web services 如何将 GPS 位置从 android 发送到 asp.net mvc - How send GPS location from android to asp.net mvc 使用json将Android连接到ASP.NET MVC - Connecting Android to ASP.NET MVC with json 如何从ASP.NET服务器向Android应用发送和接收数据以及通知,反之亦然? - How to send and receive data and notification from ASP.NET server to Android app and vise versa? 如何从我的Android应用程序传递数据并在我的ASP.NET MVC网站上接收它? - How can I pass data from my android application and receive it on my ASP.NET MVC website? 如何在android和node js之间以JSON格式发送和接收文件 - how to send and receive file in JSON between android and node js 如何从Android Studio应用程序向asp.net api控制器发送json? - How to send a json to asp.net api Controller from android studio app? 如何在Mvc 4 Web API中接收json值(例如:从Android应用程序以json形式发送的用户名和密码) - How to receive json values(for eg:username and password send as json from an android app) in Mvc 4 Web api 如何将arraylist从android发送到asp.net webservice - How send arraylist from android to asp.net webservice 如何将Android连接到ASP.NET MVC - How can I connect Android to ASP.NET MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM