Logging into a website using Android app (Java)

后端 未结 2 1074
天涯浪人
天涯浪人 2020-12-22 11:33

I am currently trying to make an app that would allow you to log into your account and view whatever data needs to be displayed.

I am not using webview but instead,

2条回答
  •  隐瞒了意图╮
    2020-12-22 12:12

    Here is the solution to this:

    class HTTPRequest implements Runnable {
    
        private URL url;
        private User user;
        private Handler handler;
        private String cookie;
    
        //**REDEFINED CONSTRUCTOR
        HTTPRequest(Handler in_handler, User in_user) {
            try {
                            url = new URL("https://yoururl.com");
    
                handler = in_handler;
                user = in_user;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public void run() {
            try {
                //**Preparing to open connection
                //**Using POST method
                //**Enabling Input & Output
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
    
                //**Setting Headers to send with POST request
                conn.setRequestProperty("Accept", "text/html");
                conn.setRequestProperty("Accept", "text/xml");
                conn.setRequestProperty("Cookie", "upassword=" + user.getPasswordHashed() + "; ulogin=" + user.getUsername());
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("charset", "UTF-8");
                conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    
                //**READING RESPONSE FROM THE SERVER:
                //**IF LOGIN WAS SUCCESSFUL, SEND MESSAGE WITH XML DATA BACK TO UI THREAD, ELSE SEND NULL TO UI THREAD
                BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
                if (isLoginSuccess(input)) {
                    StringBuilder response = new StringBuilder();
                    String tempString;
                    while ((tempString = input.readLine()) != null) {
                        response.append(tempString);
                    }
                    input.close();
                    conn.disconnect();
    
                    Message msg = Message.obtain();
                    msg.obj = response.toString();
                    handler.sendMessage(msg);
                } else if (!isLoginSuccess(input)) {
                    input.close();
                    conn.disconnect();
                    Message msg = Message.obtain();
                    msg.obj = "Wrong";
                    handler.sendMessage(msg);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //**LOGIN IS SUCCESSFUL WHEN THE RESPONSE'S FIRST LINE EQUALS XML DECLARATION
        //**RETURNS TRUE IF THAT IS THE CASE, MEANING YOU HAVE SUCCESSFULLY LOGGED IN
        private boolean isLoginSuccess(BufferedReader input) throws IOException {
            String LoginSuccess = "";
    
            String response = input.readLine();
            return response.equals(LoginSuccess);
        }
    }
    

    MainActivity.java:

    public class MainActivity extends AppCompatActivity {
    
        public static final String EXTRA_MESSAGE = "Message 1";
        public static final String EXTRA_MESSAGE_2 = "Message 2";
        Handler mainHandler;
        Thread thread;
        User user;
    
        EditText etUsername;
        EditText etPassword;
        CheckBox cbRememberMe;
        Button btLogin;
    
        SharedPreferences preferences;
        SharedPreferences.Editor SPEditor;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setTheme(R.style.LoginPageTheme);
            setContentView(R.layout.activity_main);
    
            //**DECLARATION OF SHARED PREFERENCES
            preferences = getApplicationContext().getSharedPreferences("Preferences", MODE_PRIVATE);
            SPEditor = preferences.edit();
            SPEditor.apply();
    
            //**HANDLER INSTANTIATING AND HANDLING MESSAGES FROM HTTPRequest
            mainHandler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    String message = msg.obj.toString();
                    thread.interrupt();
                    if (!message.equals("Wrong")) {
                        if (cbRememberMe.isChecked()) {
                            user.RememberLoginSuccess(preferences);
                        }
                        Intent intent = new Intent(getApplicationContext(), ProfilePageActivity.class);
                        intent.putExtra(EXTRA_MESSAGE, message);
                        intent.putExtra(EXTRA_MESSAGE_2, user);
                        startActivity(intent);
                        finish();
                    } else {
                        etUsername.setError("Wrong username or password");
                        etUsername.setText("");
                        etPassword.setText("");
                    }
                }
            };
    
            etUsername = findViewById(R.id.et_username);
            etPassword = findViewById(R.id.et_password);
            cbRememberMe = findViewById(R.id.cb_rememberMe);
            btLogin = findViewById(R.id.bt_login);
    
            btLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String temp_user = etUsername.getText().toString();
                    String temp_pass = etPassword.getText().toString();
                    if (!TextUtils.isEmpty(temp_user) && !TextUtils.isEmpty(temp_pass)) {
                        user = new User(etUsername.getText().toString(), etPassword.getText().toString());
                        thread = new Thread(new HTTPRequest(mainHandler, user));
                        thread.start();
                    } else {
                        etUsername.setError("Please, fill-out the form");
                        etUsername.setText("");
                        etPassword.setText("");
                    }
                }
            });
        }
    }
    

提交回复
热议问题