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

如何通过POST方法登录以从Android服务器访问其他API,android,login,http-post,httpclient,httpurlconnection,Android,Login,Http Post,Httpclient,Httpurlconnection,在我的应用程序中,我想实现一个登录功能,以访问服务器,获取所有必要的API集合。登录请求将通过POST方法发送。对于登录,电子邮件地址是必填字段,密码是可选的。如果我使用电子邮件地址进行身份验证,我可以从服务器获取所有api集合,如“/api/users”、“api/image”。此外,应用程序将重定向到下一页。我已尝试使用以下代码通过POSt方法从服务器进行身份验证。但代码不会发生任何变化。我既没有从服务器得到任何响应,也没有重定向到下一页。似乎我的代码中有一些问题。但我没能解决到底是什么问题

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

这里我想提一下,我不想使用任何库进行url连接

这是我登录页面的代码

    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;
    }
}
公共类登录页扩展了AppCompative活动{
private UserLoginTask mAuthTask=null;
编辑文本用户电子邮件;
编辑文本用户密码;
文本视图放弃密码;
视图进程视图;
查看loginFormView;
按钮登录;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login\u布局);
//设置登录表单
userEmail=(EditText)findViewById(R.id.email);
userPassword=(EditText)findViewById(R.id.password);
forgotPassword=(TextView)findViewById(R.id.forget\u密码);
forgotPassword.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Toast.makeText(getBaseContext(),“重定向到忘记密码链接”,Toast.LENGTH_SHORT.show();
}
});
userPassword.setOnEditorActionListener(新的TextView.OnEditorActionListener(){
@凌驾
公共布尔onEditorAction(TextView TextView、int id、KeyEvent KeyEvent){
if(id==R.id.password | | id==EditorInfo.IME_NULL){
尝试登录();
返回true;
}
返回false;
}
});
login=(按钮)findviewbyd(R.id.btn\u login);
login.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
尝试登录();
}
});
loginFormView=findviewbyd(R.id.login\u表单);
progressView=findviewbyd(R.id.login\u progress);
}
/**
*尝试登录或注册登录表单指定的帐户。
*如果存在表单错误(无效电子邮件、缺少字段等),则
*出现错误,未进行实际登录尝试。
*/
私有void attemptLogin(){
if(mAuthTask!=null){
返回;
}
//重置错误。
userEmail.setError(null);
userPassword.setError(null);
字符串email=userEmail.getText().toString();
字符串密码=userPassword.getText().toString();
布尔取消=假;
视图焦点视图=空;
//如果用户输入了有效密码,请检查密码是否有效。
如果(!TextUtils.isEmpty(密码)&&!isPasswordValid(密码)){
userPassword.setError(getString(R.string.error\u密码无效));
focusView=userPassword;
取消=真;
}
else if(TextUtils.isEmpty(密码)){
userPassword.setError(getString(R.string.error_字段_必填));
focusView=userPassword;
取消=真;
}
//检查有效的电子邮件地址。
如果(TextUtils.isEmpty(电子邮件)){
userEmail.setError(getString(R.string.error_字段_必填));
focusView=userEmail;
取消=真;
}如果(!isEmailValid(电子邮件)){
userEmail.setError(getString(R.string.error\u无效的电子邮件));
focusView=userEmail;
取消=真;
}
如果(取消){
//出现错误;请不要尝试登录并在第一次登录时集中注意力
//表单字段有错误。
focusView.requestFocus();
}否则{
//显示进度微调器,并启动后台任务以
//执行用户登录尝试。
显示进度(真实);
mAuthTask=新用户登录任务(电子邮件、密码、此);
mAuthTask.execute((Void)null);
}
}
私有布尔值isEmailValid(字符串电子邮件){
//TODO:用其他逻辑替换此逻辑
Pattern=Patterns.EMAIL\u地址;
返回pattern.matcher(email.matches();
//返回true;
}
私有布尔值isPasswordValid(字符串密码){
//TODO:用您自己的逻辑替换它
返回密码。长度()>4;
}
/**
*显示进度UI并隐藏登录表单。
*/
@TargetApi(构建版本代码蜂窝MR2)
私有void showProgress(最终布尔值显示){
//在蜂巢MR2上,我们有ViewPropertyAnimator API,它允许
//对于非常简单的动画。如果可用,请使用这些API淡入
//进度微调器。
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.HONEYCOMB\u MR2){
int shortAnimTime=getResources().getInteger(android.R.integer.config\u shortAnimTime);
loginFormView.setVisibility(show?View.go:View.VISIBLE);
loginFormView.animate().setDuration(shortAnimTime).alpha(
显示?0:1).setListener(新的AnimatorListenerAdapter(){
@凌驾
AnimationEnd上的公共无效(Animator动画){
loginFormView.setVisibility(show?View.go:View.VISIBLE);
}
});
progressView.setVisibility(显示?视图.可见:视图.消失);
progressView.a