Android 使用 HTTP post 登录,获取结果

Android Login with HTTP post, get results

我正在尝试创建一个登录功能,以便我可以验证用户。我将 Username , Password 变量传递给 AsyncTask class 但我不知道如何获取结果才能使用它们。有什么帮助吗? (由于网站限制,我贴出部分源码)

btnLogin.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if(txtUsername.getText().toString().trim().length() > 0 && txtPassword.getText().toString().trim().length() > 0)
            {
                // Retrieve the text entered from the EditText
                String Username = txtUsername.getText().toString();
                String Password = txtPassword.getText().toString();
                /*Toast.makeText(MainActivity.this,
                        Username +" + " + Password+" \n Ready for step to post data", Toast.LENGTH_LONG).show();*/

                String[] params = {Username, Password};
                // we are going to use asynctask to prevent network on main thread exception
                new PostDataAsyncTask().execute(params);

                // Redirect to dashboard / home screen.
                login.dismiss();
            }
            else
            {
                Toast.makeText(MainActivity.this,
                "Please enter Username and Password", Toast.LENGTH_LONG).show();

            }
        }
    });

然后我使用 AsynkTask 进行检查,但不知道如何获取结果并将它们存储在变量中。有帮助吗?

public class PostDataAsyncTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        // do stuff before posting data
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            // url where the data will be posted
            String postReceiverUrl = "http://server.com/Json/login.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);
            String line = null;
            String fail = "notok";

            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
            nameValuePairs.add(new BasicNameValuePair("Password", params[1]));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            line = resEntity.toString();
            Log.v(TAG, "Testing response: " +  line);

            if (resEntity != null) {

                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " +  responseStr);
                Intent Hotels_btn_pressed =  new Intent(MainActivity.this, Hotels.class);
                startActivity(Hotels_btn_pressed);
                // you can add an if statement here and do other actions based on the response
                Toast.makeText(MainActivity.this,
                        "Error! User does not exist", Toast.LENGTH_LONG).show();
            }else{
                finish();
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String lenghtOfFile) {
        // do stuff after posting data
    }
}

不是最好的代码重构,只是给你一个提示。

我会创建一个接口(我们称之为 'LogInListener'):

public interface LoginListener {
    void onSuccessfulLogin(String response);
    void onFailedLogin(String response);
}

'MainActivity' class 将实现该接口并将自己设置为 'PostDataAsyncTask' 的侦听器。因此,从主 activity 创建异步任务将如下所示:

String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
PostDataAsyncTask postTask = new PostDataAsyncTask(this);
postTask.execute(params);

我会将 'PostDataAsyncTask' class 移动到一个新文件中:

public class PostDataAsyncTask extends AsyncTask<String, String, String> {
    private static final String ERROR_RESPONSE = "notok";

    private LoginListener listener = null;

    public PostDataAsyncTask(LoginListener listener) {
        this.listener = listener;
    }

    @Override
    protected String doInBackground(String... params) {
        String postResponse = "";
        try {
            // url where the data will be posted
            String postReceiverUrl = "http://server.com/Json/login.php";

            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
            nameValuePairs.add(new BasicNameValuePair("Password", params[1]));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            postResponse = EntityUtils.toString(resEntity).trim();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return postResponse;
    }

    @Override
    protected void onPostExecute(String postResponse) {
        if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
            listener.onFailedLogin(postResponse);
        } else {
            listener.onSuccessfulLogin(postResponse);
        }
    }
}

因此,'doInBackground' returns 对 'onPostExecute' 的响应(在 UI 线程上运行),'onPostExecute' 路由结果(成功或失败)到 MainActivity,它实现了 'LogInListener' 方法:

@Override
public void onSuccessfulLogin(String response) {
    // you have access to the ui thread here - do whatever you want on suscess
    // I'm just assuming that you'd like to start that activity
    Intent Hotels_btn_pressed =  new Intent(this, Hotels.class);
    startActivity(Hotels_btn_pressed);
}

@Override
public void onFailedLogin(String response) {
    Toast.makeText(MainActivity.this,
            "Error! User does not exist", Toast.LENGTH_LONG).show();
}

我只是假设这就是你想要在成功时做的事情:开始一个新的 activity,并在失败时祝酒。