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

Android 无法使用用户名和密码在HTTP Post请求上获取JSON数据?,android,json,http-post,Android,Json,Http Post,使用get方法它是有效的,但当我尝试Post方法时,我什么也得不到。 请查看我的代码,并让我知道我做错了什么地方。 我有两个参数来传递用户名和密码 class AsyncT extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { HttpClient httpclient = new DefaultHttpClien

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

}
类AsyncT扩展了AsyncTask{
@凌驾
受保护的空位背景(空位…空位){
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://192.168.1.105:8080/api/login");
试一试{
//添加您的数据
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“用户名”adii@adii.com"));
添加(新的BasicNameValuePair(“密码”、“密码”));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
setHeader(“内容类型”,“应用程序/json;字符集=utf-8”);
setHeader(“接受”、“应用程序/json”);
//执行HTTP Post请求
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
}捕获(IOE异常){
//TODO自动生成的捕捉块
}
试一试{
BufferedReader reader=null;
如果(is!=null){
reader=新的BufferedReader(新的InputStreamReader(
//“UTF-8”“iso-8859-1”
为“UTF-8”)、8);
}
StringBuilder sb=新的StringBuilder();
弦线;
if(读卡器!=null){
而((line=reader.readLine())!=null){
sb.append(行)。append(“\n”);
}
}
如果(is!=null){
is.close();
}
结果=sb.toString();
Log.e(“sb”,结果);
}捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
返回null;
}
}

我不知道你的代码有什么问题,但你应该试试这段代码,它在这里对我非常有效。希望对你有帮助

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

}
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();
公共字符串ip=“192.168.43.114”; 公共字符串端口=“59397”; 公共HttpPost-HttpPost; 字符串服务器地址; ArrayList nameValuePairs=新的ArrayList(); JSONObject json=新的JSONObject(); 尝试在函数中实现任务,使其可重用

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

}
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;
        }
}
public int登录(字符串用户名、字符串密码){
ServerAddress=“http://“+ip+”:“+port+”/api/Users/Login”;
Log.v(“检查”、“输入法”);
试一试{
json=新的JSONObject();
put(“用户名”,UserName);
put(“密码”,PassWord);
异步任务异步任务;
AsynchServerConnection asc=新的AsynchServerConnection();
asynchTask=asc.execute(“”);
String res=asynchTask.get();
Log.v(“RES”,RES);
//res=jsonObject.toString();
//int check=Integer.parseInt(res);
Log.i(“checkR”,res+“此处”);
返回res;
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
Log.i(“检查”、“中断异常”);
返回0;
}捕获(执行例外){
//TODO自动生成的捕捉块
e、 printStackTrace();
Log.i(“检查”、“执行例外”);
返回0;
} 
捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
Log.i(“checkR”、“JSONException”);
Log.i(“checkR”,即getMessage());
返回0;
}
}
最后是异步任务类

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

}
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;
        }
    }
私有类AsynchServerConnection扩展
异步任务{
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
}
@凌驾
受保护的void onProgressUpdate(整型…值){
//TODO自动生成的方法存根
super.onProgressUpdate(值);
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
//TODO自动生成的方法存根
字符串结果=null;
试一试{
HttpClient=new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),3000);//超时限制
HttpResponse响应;
试一试{
HttpPost=新的HttpPost(服务器地址);
Log.v(标签“服务器地址:”+ServerAddress);
StringEntity se=新的StringEntity(json.toString());
setContentType(新的BasicHeader(HTTP.CONTENT_TYPE,“application/json”);
邮政实体(se);
响应=client.execute(post);
/*检查响应*/
if(响应!=null){
HttpEntity e=response.getEntity();
字符串r=EntityUtils.toString(e);
结果=r;
Log.v(“checkR”,r);
}
}捕获(例外e){
e、 printStackTrace();
Log.v(“检查”、“例外”);
Log.v(“check”,e.getMessage());
//createDialog(“错误”,“无法建立连接”);
}
返回结果;
}捕获(例外e){
//TODO自动生成的捕捉块