如何通过POST方法登录以从Server Android访问其他API

时间:2017-08-14 08:50:37

标签: android login http-post httpclient httpurlconnection

在我的应用程序中,我想实现一个登录功能来访问服务器以获取所有必要的API集合。登录请求将通过POST方法发送。对于登录,电子邮件地址是必填字段,密码是可选的。如果我使用电子邮件地址进行身份验证,我可以从服务器获取所有api colection,例如“/ api / users”,“api / image”。此外,该应用程序将重定向到下一页。我尝试使用以下代码通过POSt方法从服务器进行身份验证。但代码没有任何反应。我既没有从服务器获得任何回复,也没有重定向到下一页。我的代码似乎有些问题。但我无法解决究竟是什么问题。

在此我想提一下,我不想使用任何库进行网址连接

这是我登录页面的代码

    public class LoginPage extends AppCompatActivity {


    private UserLoginTask mAuthTask = null;

    EditText userEmail;
    EditText userPassword;
    TextView forgotPassword;
    View progressView;
    View loginFormView;
    Button login;



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

        //Set up the login form
        userEmail=(EditText)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();
            }
        });

        loginFormView = findViewById(R.id.login_form);
        progressView = findViewById(R.id.login_progress);

    }

    /**
     * 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.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, password,this);
            mAuthTask.execute((Void) null);
        }

    }
    private boolean isEmailValid(String email) {
        //TODO: Replace this with other logic
        Pattern 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;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
   @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private 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);

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

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

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }

    /**
     * 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;
        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();
            try {
                request.put("email",mEmail );
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                request.put("pass",mPassword );
            } catch (JSONException e) {
                e.printStackTrace();
            }

            String result =  connectWithServer(instance , request,mEmail,mPassword);

            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, MainOptionPage.class);
                startActivity(loginIntent);
            } else {
                userEmail.setError(getString(R.string.error_incorrect_password));
                userPassword.requestFocus();
            }
        }

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

        }
    }
    public static String connectWithServer(Activity ctx , JSONObject request, String username, String password) {
        String result ="";
        try {
            //Connect
            HttpURLConnection urlConnection = (HttpURLConnection) ((new URL("https://myurl/login")).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;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
            Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();

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

0 个答案:

没有答案