使用post方法android登录身份验证并获取其他API集合

使用post方法android登录身份验证并获取其他API集合

本文介绍了使用post方法android登录身份验证并获取其他API集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是安卓开发的新手.在我的应用程序中,我有一个登录页面,我想在其中通过 POST 方法实现身份验证功能.我有一个根地址,我必须通过它登录.我提供了一个示例网址,因为它是机密的.test.sample.com".我的协议地址是 https.那么我首先需要结合/登录".在使用此登录名进行身份验证后.我有更多的 api,比如/api/users"、api/image".如果我使用登录功能进行身份验证,我只能访问此 api.我怎样才能做到这一点.到目前为止,我已经创建了一个登录页面,但此时我还没有在这里实现任何 POST 方法.

I am very new in android developing. In my app I have a login page, where I want to implement authentication functionality by POST method. I have a root address through which I have to login. I am giving a sample url, because it is confidential. "test.sample.com". my Protol address is https. then I need to combine "/login" at first. Just after authenticating with this login. I have more apis like "/api/users", "api/image". I can only access to this api if I authenticate with the login functinality. How can I do that. So far I have created a login page, but at this moment I have not implemented any POST method here.

public class LoginPage extends AppCompatActivity{

private UserLoginTask mAuthTask = null;
    private static final String TAG = "LoginActivity";
    private AutoCompleteTextView userEmail;
    private EditText userPassword;
    private TextView forgotPassword;
    private Button login;


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

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

        userPassword=(EditText)findViewById(R.id.password);
        forgotPassword=(TextView)findViewById(R.id.forgot_password);
        forgotPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(),"Redirect to forgot password link", Toast.LENGTH_SHORT).show();
            }
        });
        userPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.password || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        login=(Button)findViewById(R.id.btn_login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
    }



    /**
     * 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.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        userEmail.setError(null);
        userPassword.setError(null);

        String email = userEmail.getText().toString();
        String password = userPassword.getText().toString();

        boolean cancel = false;
        View focusView = null;

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

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            userEmail.setError(getString(R.string.error_field_required));
            focusView = userEmail;
            cancel = true;
        } else if (!isEmailValid(email)) {
            userEmail.setError(getString(R.string.error_invalid_email));
            focusView = userEmail;
            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.
            mAuthTask = new UserLoginTask(email,password,this);
            mAuthTask.execute((Void) null);
        }

    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with other logic
        /*attern pattern = Patterns.EMAIL_ADDRESS;
        return pattern.matcher(email).matches();*/
        return true;
    }

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


    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public boolean isReachable(String address, int port, int timeoutMs) {
        try {
            Socket sock = new Socket();
            SocketAddress sockaddr = new InetSocketAddress(address, port);

            sock.connect(sockaddr, timeoutMs); // this will block no more than timeoutMs
            sock.close();

            return true;

        } catch (IOException e) { return false; }
    }

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

        private final String mEmail;
        private final String mPassword;
        boolean result = false;
        Activity instance ;

        UserLoginTask(String email, String password , Activity instance) {
            mEmail = email;
            mPassword = password;
            this.instance = instance ;
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            // TODO: attempt authentication against a network service.

            authenticateUsingServer(mEmail,mPassword);

            // TODO: register the new account here.
            return true;
        }
        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;

            if (success) {
                finish();
                Intent loginIntent = new Intent(LoginActivity.this, DummyActivity.class);
                startActivity(loginIntent);
            } else {
                userEmail.setError(getString(R.string.error_incorrect_password));
                userPassword.requestFocus();
            }
        }


    }

    public boolean authenticateUsingServer(final String mEmail, final String mPassword){
        boolean result=false ;
        try {
            if(isReachable("8.8.8.8", 53, 1000)){
                Log.e(TAG,"Authenticate using remote server");
                // Instantiate the RequestQueue.
                RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
                StringRequest strReq = new StringRequest(Request.Method.POST,
                        "https://app.com/login", new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e(TAG, "Login Response: " + response);
                        //parse your response here
                        result = true;
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Login Error: " + error.getMessage());
                        Toast.makeText(getApplicationContext(),
                                error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Log.e(TAG,"Inside getParams");

                        // Posting parameters to login url
                        Map<String, String> params = new HashMap<>();
                        params.put("email", mEmail);
                        params.put("password", mPassword);

                        return params;
                    }

                };
                // Adding request to request queue
                queue.add(strReq);
                Thread.sleep(2000);
            }
            else{
                Log.e(TAG,"Internet connection is required.");
                        /*Toast.makeText(LoginActivity.this,"Internet connectivity is required",
                                Toast.LENGTH_LONG).show();*/
                result = false;
                // TODO: exit the application
            }
        } catch (InterruptedException e) {
            return false;
        }
        return result;
    }
}

推荐答案

用以下代码替换您的 LoginTask :

Replace your LoginTask with following Code :

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

    private final String mEmail;
    private final String mPassword;
    Activity instance ;

    UserLoginTask(String email, String password , Activity instance) {
        mEmail = email;
        mPassword = password;
        this.instance = instance ;
    }

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

        JSONObject request = new JSONObject();
        request.put("email",mEmail );
        request.put("pass",mPassword );

        String result =  connectWithServer(instance , request);

        if(!TextUtils.isEmpty(result)){
            return true;
        }else{
            return false;
        }

    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(true);
        if (success) {
            finish();
            Intent loginIntent = new Intent(LoginPage.this, MainActivity.class);
            startActivity(loginIntent);
        } else {
            userEmail.setError(getString(R.string.error_incorrect_password));
            userPassword.requestFocus();
        }
    }

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

    }
}

在您的活动类中添加 connectWithServer() 方法:

public static String connectWithServer(Activity ctx , JSONObject request) {
    String result ="";
    try {
        //Connect
        HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(YOUR_SERVICE_URL)).openConnection());
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();
        urlConnection.setConnectTimeout(100000);
        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

        writer.write(request.toString());
        writer.close();
        outputStream.close();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        bufferedReader.close();
        result = sb.toString();


    } catch (UnsupportedEncodingException e){
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (JSONException e){
        e.printStackTrace();
    }
    return result;
}

这篇关于使用post方法android登录身份验证并获取其他API集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:54