在webapi和Android应用程序之间传递复杂类型

时间:2015-11-15 05:07:22

标签: android asp.net-web-api2

我是Android开发的新手。 我在使用web api消费复杂类型时遇到了问题。

情景::

我使用visual studio创建了一个web api方法,用于检查我的sql 2012数据库中的用户凭据。

API方法::

[HttpPost]
        public Login PostLogin(JObject jsonData)
        {
            dynamic json = jsonData;
            string Jusername = json.username.Value;
            string JPassword = json.Password.Value;
            int  JIsEncrypted = Convert.ToInt32(json.IsEncrypted.Value);
            Login m = db.sp_GetValidUserLoginDetails(Jusername, JPassword,JIsEncrypted)
                .Select(x => new Login()
            {
                Employee_Id = x.Employee_Id,
                Employee_Code = x.Employee_Code,
                Employee_FirstName = x.Employee_FirstName,
                Employee_LastName = x.Employee_LastName,
                Employee_EmailId = x.Employee_EmailId,
                Employee_ContactNumber = x.Employee_ContactNumber,
                IsActive = Convert.ToBoolean(x.IsActive),
                Created_Date = x.Created_Date,
                Modified_Date = x.Modified_Date,
                User_Name = x.User_Name,
                User_Password = x.User_Password,
                error = x.error

            }).ToList().FirstOrDefault();

            return m;

        }
    }

在Android项目中,我尝试了以下两种方法

方法1 ::

public String requestWebService(String serviceUrl, login logg) throws UnsupportedEncodingException {
    InputStream inputStream = null;
    JSONObject log = new JSONObject();
    String result = "";

    try {
        log.put("username", logg.username);
        log.put("Password", logg.password);
        log.put("IsEncrypted", 0);


    } catch (JSONException e) {
        e.printStackTrace();
    }
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(serviceUrl);
    String json = "";
    json = log.toString();
    httpPost.setEntity(new StringEntity(log.toString(), "UTF-8"));
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
   try {
        HttpResponse httpResponse = httpclient.execute(httpPost);

        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Toast.makeText(this, "done", Toast.LENGTH_LONG).show();
    return result;
}

方法2 ::

public String Requesting(String url, login log) throws IOException, JSONException {
 URL object=new URL(url);

        HttpURLConnection con = (HttpURLConnection) object.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(log.toString());
        wr.flush();

        StringBuilder sb = new StringBuilder();
        int HttpResult = con.getResponseCode();

            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }

            br.close();

            System.out.println(""+sb.toString());



        return null;
    }

问题::

如何将我的用户名和密码作为复杂的类型集合从Android应用程序传递到此webapi并在android项目中获取响应? 我每次都得到null JsonObject。

请帮助。谢谢提前

我已经检查了以下链接但是这里但这不适用于我的情况。 Android App with ASP.NET WebAPi Server - send complex types

2 个答案:

答案 0 :(得分:0)

因为我想要将 JSon String 发送到Web服务(webapi)。我对吗 ?如果是,那么您可以使用几行代码完成此操作。在这里,您将使用HttpUrlConnection类在webapi和Android App之间建立连接。

我在这里发布了一个示例代码,您可以使用它以JSONObject的形式将json字符串发送到webapi。

    private class BackgroundOperation extends AsyncTask<String, Void, String> {
    JSONObject josnobj ;
BackgroundOperation(JSONObject josnobj){
this.josnobj = josnobj
}
            @Override
            protected String doInBackground(String... params) 
                //Your network connection code should be here .
                String response = postCall("Put your WebService url here");
                return response ;
            }

            @Override
            protected void onPostExecute(String result) {
                //Print your response here .
                Log.d("Post Response",result);

            }

            @Override
            protected void onPreExecute() {}

            @Override
            protected void onProgressUpdate(Void... values) {}
        }

            public static String postCall(String uri) {
            String result ="";
            try {
                //Connect
                HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
                urlConnection.setDoOutput(true);
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");
                urlConnection.setRequestMethod("POST");
                urlConnection.connect();
                //Write
                OutputStream outputStream = urlConnection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
    //Call parserUsuarioJson() inside write(),Make sure it is returning proper json string .
                writer.write(josnobj.toString());
                writer.close();
                outputStream.close();

                //Read
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
                String line = null;
                StringBuilder sb = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }
                bufferedReader.close();
                result = sb.toString();
            } catch (UnsupportedEncodingException e){
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

现在,您可以使用以下代码从您的活动的onCreate()函数中调用以上内容。

    JSONObject jobj = new JSONObject();
jobj.put("name","yourname");
jobj.put("email","mail");
jobj.put("pass","pass");
    new BackgroundOperation(jobj).execute();

注意:不要忘记在manifest.xml中提及以下权限

<uses-permission android:name="android.permission.INTERNET" /> 

答案 1 :(得分:0)

最后,我得到了解决方案。希望这有助于某人。

我们需要通过添加FromBody来改变HttpPost方法的签名

[HttpPost]
    public Login PostLogin([FromBody] string jsonData)
    {
        dynamic json = jsonData;
        string Jusername = json.username.Value;
        string JPassword = json.Password.Value;
        int  JIsEncrypted = Convert.ToInt32(json.IsEncrypted.Value);
        Login m = db.sp_GetValidUserLoginDetails(Jusername,JPassword,JIsEncrypted)
            .Select(x => new Login()
        {
            Employee_Id = x.Employee_Id,
            Employee_Code = x.Employee_Code,
            Employee_FirstName = x.Employee_FirstName,
            Employee_LastName = x.Employee_LastName,
            Employee_EmailId = x.Employee_EmailId,
            Employee_ContactNumber = x.Employee_ContactNumber,
            IsActive = Convert.ToBoolean(x.IsActive),
            Created_Date = x.Created_Date,
            Modified_Date = x.Modified_Date,
            User_Name = x.User_Name,
            User_Password = x.User_Password,
            error = x.error

        }).ToList().FirstOrDefault();

        return m;

    }
}

还需要在webapi.config文件中添加以下行,以便将默认格式化程序设置为JSON

        config.Formatters.RemoveAt(0);
        config.Formatters.Add(new JsonMediaTypeFormatter());
        config.Formatters.JsonFormatter.MediaTypeMappings.Add(
        new QueryStringMapping("frmt", "json",
        new MediaTypeHeaderValue("application/json")));