2014-06-12 2 views
1

JSON 데이터 송수신 방법 Android 및 ASP.Net MVC? 로그인 활동 클래스와 JSONParser 클래스가있는 Android 로그인 애플리케이션이 있습니다. JSONParser 클래스를 사용하여 mvc 위치의 url 인 "POST"매개 변수와 my 매개 변수 username, password를 json으로 MVC에 전달합니다. 사용자 이름과 암호를 허용하는 ASP.net MVC 코드가 있는데 일치하는 항목이 발견되면 json 데이터를 "username": "admin" "success"로 반환합니다.안드로이드와 ASP.net 간의 JSON 송수신 방법 mvc

로그인 코드 활동 클래스는 다음과 같습니다

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


    } 
} 

실제로 안드로이드에서 mvc 코드로 연결되었는지 여부는 확실하지 않습니다. 또한 MVC 컨트롤러가 안드로이드 코드에 의해 Login()에서 눌려 졌는지 확실하지 않습니다. JSON 데이터가 Android에서 전송되는지, MVC 코드에서 데이터가 반환되는지 확인하는 방법은 무엇입니까?

참고 : 실제로 MVC 코드의 데이터를 비교하지 않습니다. 데이터를 반환하는 중입니다. 이것은 나의 첫번째 MVC 코드이다.

+0

이 possibilitie : 1.you 서버에서 모든 레코드를 가져 오기 및 인증 2 그와 로그인 데이터를 비교/당신이 이름을 전송하고 서버에 passwrord와 서버에서 데이터를 비교하고 부울 true 반환 유효한 경우 .. 아니면 유효하지 않은 경우 false를 반환 // 당신은 시도하고 있습니까? –

+0

나는 안드로이드에서 전달 된 데이터가 중요하지 않다. 발생하는 동작과 결과가 반환되는지 여부는 중요합니다. 실제로 사용자 이름과 암호를 서버에 보내고 비교하고 성공 메시지를 반환하거나 부울 true/false 또는 정수 값이되도록해야합니다. 내가 여기서 시도하는 것은 정수 값을 되 돌리는 것이다. – Roshan

+0

희망이 링크는 도움이됩니다. http://stackoverflow.com/questions/11014953/asp-net-web-api-authentication –

답변

0
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; 
} 
+0

이것은 안드로이드에서 JSON 파일을 서버로 보내 응답을받는 방법입니다. 당신은 응답에서 데이터를 추출 할 수 있습니다 ... –

+0

감사합니다 Wasim. 나는이 코드를 시도하고있다. 추가 질문이 있는데, wcf의 반환 데이터에 usertype이 들어 있다고 가정합니다. 어떻게 액세스 할 수 있습니까? – Roshan

+0

형제 나는 이것을 구현했다. 그러나 나는 단지 서버에 데이터를 보내고 나는 응답을 점검하지 않고있다. 그래서 지금 나는 그 부분에 대한 대답을 기울이지 않는다. 그런데 미안하다. 그러나 내가 그것을 할 것 인 때 나는 definitly 히 여기에 게시 할 것이다. :) –