如何从Android HTTP post请求中获取String?

时间:2015-06-24 11:56:14

标签: android android-asynctask http-post

我向网络服务器发送HTTP post请求登录。它返回字符串值truefalse。  AsyncTask代码:

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
    HttpResponse httpResponse;
    @Override
    protected String doInBackground(String... params) {

        String paramUsername = params[0];
        String paramPassword = params[1];


        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("myurl");

        try {


        BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("user", paramUsername);
        BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("password", paramPassword);


        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        nameValuePairList.add(usernameBasicNameValuePair);
        nameValuePairList.add(passwordBasicNameValuePAir);


            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

            httpPost.setEntity(urlEncodedFormEntity);
            httpResponse = httpClient.execute(httpPost);


            } catch (ClientProtocolException cpe) {
                System.out.println("First Exception caz of HttpResponese :" + cpe);

            } catch (IOException ioe) {
                System.out.println("Second Exception caz of HttpResponse :" + ioe);

            }




        return httpResponse.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        String s="true";
        if(result.equalsIgnoreCase(s)){
            Toast.makeText(getApplicationContext(), "Congrats! Login Successful...", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(SignIn.this, Dashboard.class);
            startActivity(intent);


        }else{
            Toast.makeText(getApplicationContext(), "Invalid Username or Password...", Toast.LENGTH_LONG).show();
        }
    }
}

OnCreate代码:

   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
    editTextUserName = (EditText) findViewById(R.id.editTextUserNameToLogin);
    editTextPassword = (EditText) findViewById(R.id.editTextPasswordToLogin);

    Button btnSignIn = (Button) findViewById(R.id.buttonSignIn);
    // btnSignIn.setOnClickListener(this);
    btnSignIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //if (v.getId() == R.id.buttonSignIn) {
                String givenUsername = editTextUserName.getEditableText().toString();
                String givenPassword = editTextPassword.getEditableText().toString();

           //     System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);
            new SendPostReqAsyncTask().execute(givenUsername, givenPassword); } }); }

doInBackground的返回值更改为httpResponse.toString()也会导致应用崩溃。 我是Android的新手,即使经过多次搜索,也似乎无法弄清楚问题。任何帮助表示赞赏。

编辑:通过执行以下操作,httpResponse可以转换为字符串:

String response = EntityUtils.toString(httpResponse.getEntity());

4 个答案:

答案 0 :(得分:2)

首先将HTTPResponse转换为String。

class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{

    HttpResponse httpResponse;
    String result 

    @Override
    protected String doInBackground(String... params) {

        String paramUsername = params[0];
        String paramPassword = params[1];

     try {

        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("Your URL");
        BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("user", paramUsername);
        BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("password", paramPassword);

        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        nameValuePairList.add(usernameBasicNameValuePair);
        nameValuePairList.add(passwordBasicNameValuePAir);

        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

        httpPost.setEntity(urlEncodedFormEntity);
        httpResponse = httpClient.execute(httpPost);

        //From here to Convert from HTTPResponse to String
        result= EntityUtils.toString(httpResponse.getEntity());

        } catch (ClientProtocolException cpe) {
            System.out.println("First Exception caz of HttpResponese :" + cpe);

        } catch (IOException ioe) {
            System.out.println("Second Exception caz of HttpResponse :" + ioe);

        }
 return result;
}

答案 1 :(得分:0)

您没有从服务器读取响应并从doInBackground()返回onPostExecute()的空值。您需要从httpresponse中读取输入流,如下所示:

String result = "";
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
     BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(inputStream));
     String line = "";
     while ((line = bufferedReader.readLine()) != null)
          result += line;
     inputStream.close();
     bufferedReader.close();
}

现在您可以从result

返回doInbackground()

答案 2 :(得分:0)

使用此请求

public String request(String url, List<NameValuePair> nameValuePairs) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        // httpPost.setHeader("encytype", "multipart/form-data");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
        httpPost.setEntity(entity);

        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        reader.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Buffer Error" + "Error converting result " + e.toString());
    }

    return json;
}

答案 3 :(得分:0)

首先检查您是否正在使用Log.d获得响应,如下所示:

httpPost.setEntity(urlEncodedFormEntity);
httpResponse = httpClient.execute(httpPost);
String response = EntityUtils.toString(httpResponse.getEntity());
Log.d("Response","Response from http:"+response);

检查Logcat代替响应显示的内容。如果没有显示任何内容,那么有两种可能性。一个是服务器端响应未正确发送。第二是可能是网络问题或网址不正确。请检查并告诉我。如果可能,还要显示logcat输出。