How to get a String from Android HTTP post request?

旧城冷巷雨未停 提交于 2019-12-08 09:39:50

问题


I am sending HTTP post request to a web server for login.It returns string value true or false. AsyncTask code :

    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 code:

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

Changing the return value of doInBackground to httpResponse.toString() also causes the app to crash. I am new to Android, and can't seem to figure out the problem even after much searching. Any help is appreciated.

Edit: The httpResponse can be converted to string by doing the following :

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

回答1:


First Covert your HTTPResponse to 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;
}



回答2:


You are not reading response from server and returning null from doInBackground() to onPostExecute(). You need to read input stream from httpresponse like this:

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

now you can return result from doInbackground()




回答3:


Use this to request

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



回答4:


First check whether you are getting response or not using Log.d as below:

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

Check in Logcat what it is showing in place of response. If it is displaying nothing then there are two possibilities. One is server side response is not sending correctly. Second is may be network problem or url not correct. Please check that and let me know. Also show the logcat output if possible.



来源:https://stackoverflow.com/questions/31025875/how-to-get-a-string-from-android-http-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!