gpt4 book ai didi

android - 如何在 Android 和 ASP.net mvc 之间发送和接收 JSON

转载 作者:行者123 更新时间:2023-12-04 23:51:30 26 4
gpt4 key购买 nike

Android 和 ASP.Net MVC 如何发送和接收 JSON 数据?
我有一个 Android 登录应用程序,它有一个登录 Activity 类和一个 JSONParser 类。
使用 JSONParser 类,我将 mvc 位置的 url、“POST”参数和我的参数用户名、密码作为 json 传递给 MVC。
我有一个接受用户名和密码的 ASP.net mvc 代码,如果找到匹配项,它将返回 json 数据为“用户名”:“管理员”,“成功”:1。

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;




}

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;

}
}

我的 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("");
}


}
}

我不确定是否真的从 android 到 mvc 代码建立了连接。我也不确定Android代码是否在Login()处击中了MVC Controller 。
如何确保 JSON 数据是从 Android 发送的,以及数据是从 MVC 代码返回的?

注意:我实际上并没有比较 MVC 代码中的数据。我只是返回数据。这是我的第一个 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;
}

关于android - 如何在 Android 和 ASP.net mvc 之间发送和接收 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24177400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com