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

时间:2017-07-24 09:25:07

标签: android api authentication post httpurlconnection

我是android开发的新手。在我的应用程序中,我有一个登录页面,我想通过POST方法实现身份验证功能。我有一个根地址,我必须通过该地址登录。我正在提供一个示例网址,因为它是保密的。 “test.sample.com”。我的Protol地址是https。然后我需要首先结合“/ login”。在使用此登录进行身份验证之后。我有更多api像“/ api / users”,“api / image”。如果我使用登录功能进行身份验证,我只能访问此API。我怎样才能做到这一点。到目前为止,我已经创建了一个登录页面,但此时我还没有在这里实现任何POST方法。

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;
    }
}

2 个答案:

答案 0 :(得分:0)

使用以下代码替换您的LoginTask:

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

    }
}

在Actvity类中添加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;
}

答案 1 :(得分:0)

这里使用:

首先检查互联网是否可用。

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 boolean authenticateUsingServer(final String mEmail, final String mPassword){
            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,
                            URL_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;
        }

然后从Async任务中调用它:

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

            authenticateUsingServer(mEmail,mPassword);

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