1

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

}
G.I Joe
  • 77
  • 1
  • 11
  • Can you please post a log of what you're getting? What are you using for the server side? Also, are you sure the form only has a login/password? – Laur Ivan Jul 25 '16 at 11:03
  • the form has username and password only,server side is ROR and PHP @LaurIvan – G.I Joe Jul 25 '16 at 11:17
  • `Log.e("sb",result);` What does that print? `"application/json; charset= utf-8");`You are telling the server that you are going to send json text. But you are not sending json at all. You are sending name value pairs. You better show your php script. – greenapps Jul 25 '16 at 11:39
  • Check out the form in a browser. Frameworks tend to add extra (hidden) fields for e.g. CSRF protection. – Laur Ivan Jul 25 '16 at 11:49

1 Answers1

2

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.

Aimal Khan
  • 979
  • 10
  • 23
  • It could be an issue with your wamp server! @G.IJoe http://stackoverflow.com/questions/6876266/java-net-connectexception-connection-refused – Aimal Khan Jul 25 '16 at 11:38
  • @G.IJoe hey comment that line its of no use to you, apologies for the inconvenience. – Aimal Khan Jul 26 '16 at 06:18
  • this should be my output { "roles" : [ "ROLE_CAN_ADD", "ROLE_CAN_UPLOAD", "ROLE_USER" ], "username" : "adii@adii.com", "access_token" : "bbggu9v7lbu4ibkjfkbjlntu1ajmfj6i" } – G.I Joe Jul 26 '16 at 06:27
  • are you still returning check? or 0? @G.IJoe – Aimal Khan Jul 26 '16 at 06:42
  • return Check rather than 0. do not change any code! @G.IJoe I'm sorrry i'm trying my best to help you out – Aimal Khan Jul 26 '16 at 06:59
  • int check = Integer.parseInt(res); I commented this line.AS you told @AimalKhan so I cannot return check – G.I Joe Jul 26 '16 at 07:01
  • It is a string so I did like this return Integer.parseInt(res); build is successful but I did not see the output @AimalKhan – G.I Joe Jul 26 '16 at 07:06
  • @G.IJoe Just replace your code with return res; and see the results in the log. It will return the data in json format! – Aimal Khan Jul 26 '16 at 07:11
  • @G.IJoe do not convert your string to Integer for no reason! – Aimal Khan Jul 26 '16 at 07:12
  • No,here res is a string and return type is int. So I can't return string @AimalKhan – G.I Joe Jul 26 '16 at 07:15
  • @G.IJoe change the return type to string :D – Aimal Khan Jul 26 '16 at 07:16
  • @G.IJoe Did you made the changes? – Aimal Khan Jul 26 '16 at 07:39
  • @G.IJoe I'll provide a sample code code to you if you're okay with that – Aimal Khan Jul 26 '16 at 07:42
  • 1
    @G.IJoe before i do that, rate my answer as it solved your issue right? :) – Aimal Khan Jul 26 '16 at 07:45
  • @G.IJoe Thank you. Where do you need the code? Right here? or Some other plateform? – Aimal Khan Jul 26 '16 at 07:48
  • @G.IJoe could you be more descriptive? – Aimal Khan Jul 26 '16 at 08:33
  • the response I was getting was 400 from this line response = client.execute(post); // response.getStatusLine().getStatusCode(); Log.e("response", String.valueOf(response.getStatusLine().getStatusCode()));@AimalKhan – G.I Joe Jul 26 '16 at 08:37
  • @G.IJoe Tell me what are you passing to this decode function? a Json object or a json String? – Aimal Khan Jul 26 '16 at 08:40
  • Okay @G.IJoe, are you putting the variable names right i.e. userName = json.getString("userName"); ?? because you need to put the exact variable names which are provided by the Json String. – Aimal Khan Jul 26 '16 at 08:45
  • @G.iJoe one more thing, you cant really pass a Json string to a function which expects a json object, you'll have to convert it first. I'm not sure but you should look for it, what is the type of the parameter which you're passing? Is it string? is it a jsonObject? – Aimal Khan Jul 26 '16 at 08:47
  • let say I just want to see the output in JSON format only.No decoding.There also I am getting response code 400 @AimalKhan – G.I Joe Jul 26 '16 at 08:48
  • @G.IJoe A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules. – Aimal Khan Jul 26 '16 at 08:55
  • here I am sending only username and password.So it means these things do not follow the rule.@AimalKhan – G.I Joe Jul 26 '16 at 08:59
  • @G.IJoe Yes it could be, An error in a parameter value is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error. – Aimal Khan Jul 26 '16 at 09:03