Android登录HTTP发布,获得结果

时间:2015-01-28 13:56:26

标签: android login android-asynctask

我正在尝试创建一个Login功能,以便我可以验证用户。我将用户名,密码变量传递给AsyncTask类,但我不知道获取结果以便使用它们。有帮助吗? (由于网站限制,我发布了部分源代码)

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

1 个答案:

答案 0 :(得分:0)

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

我会创建一个界面(让我们称之为&#39; LogInListener&#39;):

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

&#39; MainActivity&#39; class将实现该接口并将其自身设置为监听器&quot; PostDataAsyncTask&#39;。因此,从主活动创建异步任务将如下所示:

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

我会移动&#39; PostDataAsyncTask&#39;将类分成新文件:

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

所以,&#39; doInBackground&#39;将响应返回给&#39; onPostExecute&#39; (在UI线程上运行)和&#39; onPostExecute&#39;将结果(成功或失败)路由到MainActivity,MainActivity实现了&#39; LogInListener&#39;方法:

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

我只是假设你在成功时想做的事情:开始一项新活动,并在失败时显示祝酒。