如何从Android HTTP post请求获取String? [英] How to get a String from Android HTTP post request?

查看:168
本文介绍了如何从Android HTTP post请求获取String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 代码:

   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的新手,即使经过多次搜索,似乎无法弄清楚问题。任何帮助都表示赞赏。

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.

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

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

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


推荐答案

首先将HTTPResponse转换为字符串。

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

这篇关于如何从Android HTTP post请求获取String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆