无法使用用户名和密码获取HTTP Post请求的JSON数据?

时间:2016-07-25 11:00:12

标签: android json http-post

使用get方法它正在工作,但当我尝试Post方法时,我什么都没得到。 请查看我的代码,让我知道我在哪里做错了什么 我有两个参数来传递用户名和密码。

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

}

1 个答案:

答案 0 :(得分:2)

我不知道您的代码有什么问题,但您应该尝试使用此代码,它在这里与我完美配合。希望它能帮到你

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

尝试在函数中实现您的任务,以便它可以重用。

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

最后是异步任务类

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

现在当你获得数据时,你需要它从json格式解码它。这是一个示例类和一个DECODEJSON函数,尝试根据你自己的要求实现它

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


    }
}
    //

如果问题仍然存在,请告诉我。