1

我有两个活动。

主要活动运行应用程序并初始化 http get 请求代码并将来自 JSON 的响应解析为字符串。

getmethod 活动使用 http get 方法连接到服务器并将响应发送回我的主要活动。

如何创建登录方法,用户手动输入用户名和密码并将其传递给 get 方法?

4

1 回答 1

1

您可以将此代码添加到您的主要活动中 - 它会为您完成所有繁重的工作。

/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPostExecute(final Boolean success) {
        if (success == true) {
            //Do whatever your app does after login

        } else {
            //Let user know login has failed
        }
    }

    @Override
    protected Boolean doInBackground(String... login) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "YOUR_ADDRESS_HERE.COM");
        String str = null;
        String username = login[0];
        String password = login[1];

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            HttpResponse response = httpclient.execute(httppost);
            str = EntityUtils.toString(response.getEntity());

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

                    //Whatever parsing you need to do on the response
                    //This is an example if the webservice just passes back a String of "true or "false"

        if (str.trim().equals("true")) {

            return true;
        } else {
            return false;

        }
    }

您可以通过以下方式创建此对象:

  UserLoginTask mAuthTask = new UserLoginTask();

使用以下命令开始请求(也许从登录按钮中放入 OnClick 事件?):

mAuthTask.execute(mUsername, mPassword);
于 2012-12-10T11:14:43.090 回答