Android(Java)实现网站登录功能技术求助
How to Implement Website Login with Jsoup in Your Android App
Hey there! Let's walk through fixing your login flow step by step—you're already using Jsoup, which is perfect for this job. Right now your code is just fetching the login page with a GET request, but we need to send a POST request with your username and password, then handle the response properly. Here's what to do:
First, Figure Out the Login Request Details
Before coding, you need to know exactly what data the website expects for login:
- Open your target website in a browser, hit F12 to open Developer Tools, then go to the Network tab.
- Enter your username/password and click login. Look for the POST request (usually sent to a URL like
/loginor/auth). - Check the Form Data section—note the names of the fields (e.g., it might be
usernameandpassword, oruser_emailanduser_pass). These are the keys you'll use in your Jsoup request.
Fix Your AsyncTask & Login Logic
Your current code jumps to the next activity immediately, before the network request finishes. We'll fix that, plus add the POST login logic:
Updated MainActivity Code
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.Toast; 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); EditText etUsername = findViewById(R.id.etUsername); EditText etPass = findViewById(R.id.etPass); Button btLogin = findViewById(R.id.btLogin); btLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = etUsername.getText().toString().trim(); String password = etPass.getText().toString().trim(); // Don't run login if fields are empty if (!username.isEmpty() && !password.isEmpty()) { new LoginTask().execute(username, password); } else { Toast.makeText(MainActivity.this, "Please fill in both fields", Toast.LENGTH_SHORT).show(); } } }); } // Updated AsyncTask to handle login POST and return status private class LoginTask extends AsyncTask<String, Void, String> { private String nextPageHtml; @Override protected String doInBackground(String... params) { String username = params[0]; String password = params[1]; String loginUrl = "https://your-actual-login-endpoint"; // Replace with your site's login URL String result = "error"; try { // Send POST request with login credentials Document loginResponse = Jsoup.connect(loginUrl) .data("username", username) // Replace with actual field name from your site .data("password", password) // Replace with actual field name from your site .post(); // This sends the POST request like a browser does // Check if login succeeded String responseContent = loginResponse.text(); if (responseContent.contains("Successful login")) { result = "success"; // Fetch the next page (Jsoup auto-saves session cookies for authenticated access) Document nextPage = Jsoup.connect("https://your-target-data-page").get(); nextPageHtml = nextPage.toString(); } } catch (Exception e) { e.printStackTrace(); result = "exception"; } return result; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); switch (result) { case "success": data = nextPageHtml; // Navigate to UserAccount only after successful login Intent intent = new Intent(MainActivity.this, UserAccount.class); intent.putExtra("data", data); startActivity(intent); break; case "error": Toast.makeText(MainActivity.this, "Wrong username or password", Toast.LENGTH_SHORT).show(); break; case "exception": Toast.makeText(MainActivity.this, "Network error, please try again", Toast.LENGTH_SHORT).show(); break; } } } }
Key Changes Explained
- AsyncTask Upgrade: We changed
AsyncTask<Void, Void, Void>toAsyncTask<String, Void, String>so we can pass username/password and return a login status. - POST Request:
Jsoup.connect(loginUrl).data(...).post()sends your credentials to the login endpoint, mimicking a browser's form submission. - Session Handling: Jsoup automatically saves session cookies, so your subsequent request to the data page will be authenticated.
- Proper Flow: We only navigate to
UserAccountafter the login request finishes and succeeds—no more jumping before data is ready!
Critical Checks
- Add Internet Permission: Make sure this line is in your
AndroidManifest.xml:<uses-permission android:name="android.permission.INTERNET" /> - Field Name Accuracy: Replace
"username"and"password"in the.data()calls with the actual field names you found in your browser's Developer Tools. If the site uses a CSRF token, you'll need to fetch that from the login page first and include it in your POST request. - AsyncTask Deprecation Note: AsyncTask is deprecated in newer Android versions. For long-term projects, consider using Coroutines or OkHttp with background threads, but this code works great for learning.
内容的提问来源于stack exchange,提问作者vt-dev0
相关产品推荐
相关产品推荐

