通过API

时间:2015-04-28 09:00:09

标签: java android api login android-asynctask

我试图在Android中创建LoginActivity。 我使用Android Studio提供的标准LoginActivity模板。

我所做的是给用户一个很好的LoginActivity,当登录成功时,应该显示一个显示WebSite的WebView的活动。

现在我有一个Asynchron任务,所有的"魔法"似乎发生了。

 public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.



        try {
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }



        for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }

        // TODO: register the new account here.
        return false;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
}

这里的用户名和密码只是编译为数组的值。

我的第一个问题是,我更改了该任务的所有内容,比如添加一个简单的Toast,导致我的应用程序崩溃......

这是我第一次实施登录,但我是对的,我的登录算法必须是那个任务吗?

多数民众赞成我的naxt问题,我如何提出请求,为我的r使用空的登录令牌并调用函数getLoginToken?

本网站的API为我提供了这个RequestLink:

www.pentle.com/api.php?c=json&r={"request":"getLoginToken","validation":{"type":"token","client":"YOUR_APP","token":"","token_id":0,"user_id":0}}&username=YOUR_USERNAME&password=YOUR_PASSWORD

请求将返回一个像这样的json对象:

{
   "token_id":0,
   "user_id":0,
   "token":"THE_TOKEN"
}

我尝试了this解决方案,但它没有用。当我尝试使用HttpClient时,它有一条线穿过它(击中/划掉?)。而我的应用程序崩溃......

也许有人可以了解如何使用Asynchron Task,以及如何使用RequestLink进行登录。

这对我来说非常重要,这是有效的!

编辑: 感谢@danny,我的代码现在看起来像这样:

package com.pentle.pentle2;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.ArrayList;
import java.util.List;


/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> {

    public String test = "";

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
private static final String[] DUMMY_CREDENTIALS = new String[]{
        "foo@example.com:hello", "bar@example.com:world"
};
/**
 * Keep track of the login task to ensure we can cancel it if requested.
 */
private UserLoginTask mAuthTask = null;

// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // Set up the login form.
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
    populateAutoComplete();

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        }
    });

    Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptLogin();
        }
    });

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);
}

private void populateAutoComplete() {
    getLoaderManager().initLoader(0, null, this);
}


/**
 * Attempts to sign in or register the account specified by the login form.
 * If there are form errors (invalid email, missing fields, etc.), the
 * errors are presented and no actual login attempt is made.
 */
public void attemptLogin() {
    if (mAuthTask != null) {
        return;
    }

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;


    // Check for a valid password, if the user entered one.
    if (TextUtils.isEmpty(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for empty Username
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        showProgress(true);
        mAuthTask = new UserLoginTask(email, password);
        mAuthTask.execute((Void) null);
    }
}

private boolean isEmailValid(String email) {
    //TODO: Replace this with your own logic
    return email.contains("@");
}

private boolean isPasswordValid(String password) {
    //TODO: Replace this with your own logic
    return password.length() > 4;
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

            // Select only email addresses.
            ContactsContract.Contacts.Data.MIMETYPE +
                    " = ?", new String[]{ContactsContract.CommonDataKinds.Email
            .CONTENT_ITEM_TYPE},

            // Show primary email addresses first. Note that there won't be
            // a primary email address if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    List<String> emails = new ArrayList<String>();
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        emails.add(cursor.getString(ProfileQuery.ADDRESS));
        cursor.moveToNext();
    }

    addEmailsToAutoComplete(emails);
}

@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {

}

private interface ProfileQuery {
    String[] PROJECTION = {
            ContactsContract.CommonDataKinds.Email.ADDRESS,
            ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
    };

    int ADDRESS = 0;
    int IS_PRIMARY = 1;
}


private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
    //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
    ArrayAdapter<String> adapter =
            new ArrayAdapter<String>(LoginActivity.this,
                    android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

    mEmailView.setAdapter(adapter);
}

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

    private final String mEmail;
    private final String mPassword;


    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
        test = "1";
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.
    String response;
    HttpClient Client = new DefaultHttpClient();
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try
        {
            test = "2";
            HttpPost postMethod = new HttpPost("www.pentle.com/api.php?c=json&r={request:getLoginToken,validation:type:token,client:Pentle_Android,token:,token_id:0,user_id:0}}&username="+mEmail+"&password=" + mPassword);
            //_email and _password are String values from TextView:
            test = "3";
            //postMethod.setEntity(new StringEntity("&username="+mEmail+"&password=" + mPassword));
            test = "4";
            postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
            //here is the reponse, you can check it:
            response = Client.execute(postMethod, responseHandler);

        }

        catch(Exception ex)
        {
            //Login to server failed...
            ex.printStackTrace();
        }



        /*try {
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }

        for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }*/

        // TODO: register the new account here.
        return false;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        Toast.makeText(getApplicationContext(), test, Toast.LENGTH_SHORT).show();

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
    }
}

如果用户没有找到用户,但是pw不正确,或者登录成功,则应该返回。如果成功,则应显示带有WebView的活动。

现在它在HttpPost postMethod = new HttpPost("www.pentle.com/api.php?c=json&r={request:getLoginToken,validation:type:token,client:Pentle_Android,token:,token_id:0,user_id:0}}&username="+mEmail+"&password=" + mPassword);失败了。是因为我试图在后台运行它吗? 字符串test显示在PostExecute的Toast中,以查看ist停止的位置。

我是否正确使用API​​请求?

2 个答案:

答案 0 :(得分:0)

@Denis Pramme

请尝试使用此代码并告知我们:

public class LoginActivity extends Activity 
{
.....

private void SignInMethod()
{
 new Thread(new Runnable()
    {
        public void run()
        {
        try
          {
        HttpPost postMethod = new HttpPost("*URL TO YOUR API SERVER*" +   "Authenticate");
        //_email and _password are String values from TextView:
        postMethod.setEntity(new StringEntity("grant_type=password&username=" + _email + "&password=" + _password));
        postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
        //here is the reponse, you can check it:
        response = httpClient.execute(postMethod, resonseHandler);
          }

          catch(Exception ex)
          {
           //Login to server failed...
             ex.printStackTrace();
          }
        }
    }).start();
}

}

答案 1 :(得分:0)

@DennisPramme,好的,请改行:

String response = httpClient.execute(postMethod, resonseHandler);

到这一行:(它将显示从服务器返回的状态):

HttpResponse responseFromServer = httpClient.execute(postMethod);
int status = responseFromServer.getStatusLine().getStatusCode();