简体   繁体   English

使用 Android 应用程序 (Java) 登录网站

[英]Logging into a website using Android app (Java)

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, for displaying information I will be parsing data from HTML and then working from there, extracting data that I need to display.我没有使用 webview,而是为了显示信息,我将从 HTML 解析数据,然后从那里工作,提取我需要显示的数据。 I will post code from my app below.我将在下面发布我的应用程序中的代码。

What I need help with is figuring out how to log into the website with my app.我需要帮助的是弄清楚如何使用我的应用程序登录网站。

Basically, steps would look like that:基本上,步骤如下所示:

1.Enter Username 1.输入用户名

2.Enter Password 2.输入密码

3.Press Login Button 3.按登录按钮

4.Send Username&Password to the website 4.发送用户名和密码到网站

5.If - website returns "Successful login", proceed and parse next page from HTML, Else - display "Wrong username or password" 5.如果 - 网站返回“登录成功”,继续并从 HTML 解析下一页,否则 - 显示“用户名或密码错误”

However, I have no idea how to make my app log in, or at least input data in the website's login fields so that I can at least get a response in some way.但是,我不知道如何让我的应用程序登录,或者至少在网站的登录字段中输入数据,以便我至少可以以某种方式得到响应。

I am very new to this, so please, at least point me in the right direction so that I can figure it out.我对此很陌生,所以请至少指出我正确的方向,以便我弄清楚。 Thank you very much.非常感谢。

    package com.example.app;

    import androidx.appcompat.app.AppCompatActivity;

    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;

    public class MainActivity extends AppCompatActivity {
        String data;

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

            TextView LoginTitle = findViewById(R.id.tvLoginTitle);
            EditText Username = findViewById(R.id.etUsername);
            EditText Password = findViewById(R.id.etPass);
            Button Login = findViewById(R.id.btLogin);

            Login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Parse().execute();
                    Intent intent = new Intent(MainActivity.this,UserAccount.class);
                    intent.putExtra("data",data);
                    startActivity(intent);
                }
            });

        }

        public class Parse extends AsyncTask<Void, Void, Void> {
            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    Document WebPage = Jsoup.connect("https://myurl").get();
                    Log.d("data", WebPage.toString());
                    data=WebPage.toString();
                } catch(Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            //Used in guide, however, my implementation of the app doesn't seem to need this.
        }
    }
}

I am not sure what you are trying to do by logging the content of the WebPage there.我不确定您通过在那里记录网页的内容来尝试做什么。 What you need to do first is check if the "browser" has Javascript enabled but in your case this is moot because you are using your own WebView.您首先需要做的是检查“浏览器”是否启用了 Javascript,但在您的情况下,这没有实际意义,因为您使用的是自己的 WebView。 It would still be wise to just check if JS is enabled.只检查是否启用了 JS 仍然是明智的。

The next step obviously involves using JS since I asked you to check if it is enabled.下一步显然涉及使用 JS,因为我要求您检查它是否已启用。 Here is the code but note I did nor test this but it is a step in the right direction:这是代码,但请注意我没有对此进行测试,但这是朝着正确方向迈出的一步:

    public void loginUser(View view) {

        InputMethodManager inputMan = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(layout.getWindowToken(), 0);


        webView.loadUrl("https://yourwebsite.net");
        webView.setVisibility(View.INVISIBLE);
        webView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                webView.loadUrl("javascript: {" + "document.getElementById('login_account').value = '" + "USERNAME" + "';" + "document.getElementById('login_password').value = '" + "PASSWORD" + "';" + "document.getElementById('submit').click();" + "};");
                 }

            public void onPageFinished2(WebView view, String url) {
                webView.loadUrl(url);
            }
        });

        webView.clearCache(true);
        webView.clearHistory();


    WebView webView2 = (WebView) this.findViewById(R.id.web_view);

    String url = "https://yourwebsite.net";
    webView2.loadUrl(url);

}

Some points to note: change the values login_account and login_password to something that a person cannot easily guess for security.需要注意的几点:将值 login_account 和 login_password 更改为人们无法轻易猜到的安全性。

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 = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";

        String response = input.readLine();
        return response.equals(LoginSuccess);
    }
}

MainActivity.java: 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("");
                }
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM