0

I am new to android development. I have an issue with consuming complex types from web api.

Scenario::

I have created a web api method using visual studio for checking user credentials from my sql 2012 database.

API method::

[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;

        }
    }

In Android project I have tried below two methods

Method 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;
}

Method 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;
    }

Question::

How can I pass my username and password as complex type collection from android app to this webapi and get the response back in android project? I am getting null JsonObject everytime.

Please help.Thanks in advance

I have checked below link but here but this isnt working in my case. Android App with ASP.NET WebAPi Server - send complex types

Community
  • 1
  • 1

2 Answers2

0

As I am getting you want to send JSon String to a web service (webapi) . Am I right ? If yes then you can do this using few lines of code . Here you will use HttpUrlConnection class to establish connection between webapi and your Android App .

I am posting a sample code here using which you can send json string in the form of JSONObject to 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;
        }

Now you can call above from from your activity's onCreate() function using below code .

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

Note : Don't forget to mention below permission in your manifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 
Shishupal Shakya
  • 1,632
  • 2
  • 18
  • 41
0

Finally I got the solution for this.Hope this helps someone.

We need to change the signature of HttpPost method by adding FromBody

[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;

    }
}

Also below lines needs to be added in webapi.config file in order to set the default formatter to JSON

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