本文介绍了Android的HTTP GET方法登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个活动。

主要活动运行的应用程序和初始化的HTTP GET请求code和解析来自JSON响应转换成字符串。

The main activity runs the app and initialises the http get request code and parses the response from JSON into a string.

实现getMethod活动使用一个HTTP GET方法连接到服务器并发送回响应我的主要活动。

The getmethod activity uses a http get method to connect to the server and sends the response back to my main activity.

如何创建一个登录方法,在用户手动输入用户名和密码,这是传递到get方法?

How can I create a log in method, where the user enters their username and password manually and this is passed onto the get method?

推荐答案

您可以添加此code到您的主要活动 - 它会做所有繁重的你

You can add this code to your main activity - it will do all the heavy lifting for you.

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

        }
    }

您可以通过创建该对象:

You can create this object by:

  UserLoginTask mAuthTask = new UserLoginTask();

先从请求(或许是放在一个onclick事件从一个登录按钮):

Start the request with (perhaps put in an OnClick event from a login button?):

mAuthTask.execute(mUsername, mPassword);

这篇关于Android的HTTP GET方法登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:03