G.I Joe G.I Joe - 4 months ago 12
Android Question

Unable to get JSON data on HTTP Post request with username and password?

Using get method it is working but when I tried Post method I am getting nothing.
Please have a look at my code and let me know where or what I am doing wrong.

I have two parameters to pass username and password.

class AsyncT extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {


HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.105:8080/api/login");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "adii@adii.com"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("content-type", "application/json; charset= utf-8");
httppost.setHeader("Accept", "application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();


} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(
//"UTF-8" "iso-8859-1"
is, "UTF-8"), 8);
}
StringBuilder sb = new StringBuilder();
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");


}
}
if (is != null) {
is.close();

}
result = sb.toString();

Log.e("sb",result);

} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}

}

Answer

I've no idea what is wrong with your code but you should try this code, it works perfectly here with me. Hope it helps you

public String ip = "192.168.43.114";
public String port = "59397";

public HttpPost httppost;
String ServerAddress;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

JSONObject json = new JSONObject();

Try implementing your task in functions so it becomes reusable.

public int login(String username, String password)  {
        ServerAddress = "http://"+ip+":"+port+"/api/Users/Login";
        Log.v("check","inLoginMethod");
        try {

            json = new JSONObject();
            json.put("UserName", username);
            json.put("PassWord", password);

            AsyncTask<String, Integer, String> asynchTask;
            AsynchServerConnection asc = new AsynchServerConnection();
            asynchTask = asc.execute("");
            String res = asynchTask.get();
            Log.v("RES", res);

            //res = jsonObject.toString();
            //int check = Integer.parseInt(res);
            Log.i("checkR", res + "here");
            return res;

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("checkR", "Interrupted exception");
            return 0;
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("checkR", "ExecutionException");
            return 0;
        } 
        catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("checkR", "JSONException");
            Log.i("checkR", e.getMessage());
            return 0;
        }
}

and finally the async task class

private class AsynchServerConnection extends
            AsyncTask<String, Integer, String> {

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub

            super.onProgressUpdate(values);
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            String result = null;
            try {
                 HttpClient client = new DefaultHttpClient();

                    HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000); //Timeout Limit
                    HttpResponse response;


                    try {
                         HttpPost post = new HttpPost(ServerAddress);
                         Log.v(TAG, "server Addr: "+ServerAddress);

                        StringEntity se = new StringEntity( json.toString());
                        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

                        post.setEntity(se);
                        response = client.execute(post);

                        /*Checking response */
                        if(response!=null){

                            HttpEntity e = response.getEntity();
                            String r =EntityUtils.toString(e);
                            result = r;
                            Log.v("checkR", r);
                        }

                    } catch(Exception e) {
                        e.printStackTrace();
                        Log.v("check", "exception");
                        Log.v("check", e.getMessage());
                        //createDialog("Error", "Cannot Estabilish Connection");
                    }

                return result;

            } catch (Exception e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            }
            return result;
        }
    }

Now when you get the data, you'll need it to decode it from json format, Here is a sample class and a DECODEJSON function, try implementing it considering your own requirements

package com.example.aimalkhan.vegegardenandroidapp;

/**
 * Created by Aimal Khan on 12/28/2015.
 */

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Users {

    private static String userName;
    private static String password;
    private static String contactNumber;
    private static String emailId;
    private static String lat;
    public static String longg = "";
    private static String address;

    public static String getPlantNames() {
        return plantNames;
    }

    public static void setPlantNames(String plantNames) {
        Users.plantNames = plantNames;
    }

    private static String plantNames;

    public String getLongg() {
        Log.v("checkR", longg + "in users class! - getting long");
        return longg;
    }

    public void setLongg(String longg) {
        Log.v("checkR", longg + "in users class! - seting long");
        this.longg = longg;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        Users.address = address;
    }

    public String getLat() {
        return lat;
    }

    public void setLat(String lat) {
        this.lat = lat;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        Log.v("checkR", "in users class" + userName);
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;

    }

    /*var $id="";
        var $type="";
        var $firstName="";
        var $lastName="";
        var $contactNumber="";
        var $emailId="";
        var $address="";
        */

    /*        public Users(String id,String type)
            {
                this.id=id;
                this.type=type;
            }*/
    public Users() {
    }

    public void decodeJson(JSONObject json) {
        try {
            userName = json.getString("userName");
            setUserName(userName);
            password = json.getString("userPassword");
            setPassword(password);
            contactNumber = json.getString("contactInfo");
            setContactNumber(contactNumber);
            emailId = json.getString("emailID");
            Log.v("checkR", emailId + "in users class!");
            setEmailId(emailId);
            lat = json.getString("userLat");
            setLat(lat);
            longg = json.getString("userLong");
            Log.v("checkR", longg + "in users class!");
            address = json.getString("userAddress");
            setAddress(address);
            Log.v("checkR", address + "in users class!");
            setLongg(longg);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static List<String> plantsT;
    public void decodeJsonUserPlants(String json) {
        String[] arr;
        plantsT = new ArrayList<String>();
        Log.v("check123",json.toString()+"           json");
        try {
            JSONObject jsonObject = new JSONObject(json);
            arr = jsonObject.getString("plantNames").split(",");

            for (int i = 0; i < arr.length; i++) {
                arr[i] = arr[i].replaceAll("\"", "").replaceAll("\\[", "").replaceAll("\\]", "");
                Log.v("check123",arr[i].toString()+"           loop");
                plantsT.add(arr[i]);
//                plantsT.add(arr.toString());
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}
    //

Let me know if the problem still persists.