Android HTTP GET Login method



我有两个活动。

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

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

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

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

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

相关内容

  • 没有找到相关文章

最新更新