如何实现Android后台登录校园网页并在TextView展示指定数据
Hey there! Let's walk through exactly how to build this Android app—from logging into your university's student portal in the background, grabbing that course schedule data, and displaying it in a TextView. I'll break it down into actionable steps with code examples to make it concrete.
First, you need to enable internet access and add libraries to handle network requests and HTML parsing:
- Add Internet Permission: Pop this into your
AndroidManifest.xmlright above the<application>tag:<uses-permission android:name="android.permission.INTERNET" /> - Add Dependencies: Open your app-level
build.gradle(Module level) and add these lines to thedependenciesblock (use the latest versions if available):// For network requests implementation 'com.squareup.okhttp3:okhttp:4.11.0' // For parsing HTML implementation 'org.jsoup:jsoup:1.17.2'
Most university portals use a POST request to handle login, with form data for username/password. You'll need to:
- Capture the exact form field names (check your portal's login page source—look for
<input>tags withnameattributes likeusername,password, or maybestudent_id). - Persist cookies to maintain your logged-in session (OkHttp's
CookieJarhandles this automatically).
Here's a Java example for the login flow:
// Initialize OkHttpClient with cookie persistence OkHttpClient client = new OkHttpClient.Builder() .cookieJar(new CookieJar() { private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>(); @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { cookieStore.put(url.host(), cookies); } @Override public List<Cookie> loadForRequest(HttpUrl url) { List<Cookie> cookies = cookieStore.get(url.host()); return cookies != null ? cookies : new ArrayList<>(); } }) .build(); // Build the login POST request RequestBody formBody = new FormBody.Builder() .add("username", "your_student_id") .add("password", "your_password") // Add any other hidden fields from the login form (like CSRF tokens) .add("csrf_token", "extracted_csrf_value") .build(); Request loginRequest = new Request.Builder() .url("https://your-university-portal.com/login") .post(formBody) .build(); // Execute the login asynchronously (never run network calls on the main thread!) client.newCall(loginRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Handle login failure (e.g., show toast on main thread) runOnUiThread(() -> Toast.makeText(MainActivity.this, "Login failed", Toast.LENGTH_SHORT).show()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { // Login succeeded—now fetch the course schedule page fetchCourseSchedule(client); } else { runOnUiThread(() -> Toast.makeText(MainActivity.this, "Invalid credentials", Toast.LENGTH_SHORT).show()); } } });
Once logged in, you'll request the course schedule page and parse its HTML with Jsoup. First, inspect your portal's course page to find the HTML structure holding the class times—look for:
- A
<table>with a uniqueclassorid(e.g.,class="course-schedule-table") <div>tags with specific classes wrapping each course entry
Here's how to parse the page:
private void fetchCourseSchedule(OkHttpClient client) { Request scheduleRequest = new Request.Builder() .url("https://your-university-portal.com/course-schedule") .build(); client.newCall(scheduleRequest).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to load schedule", Toast.LENGTH_SHORT).show()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String html = response.body().string(); // Parse HTML with Jsoup Document doc = Jsoup.parse(html); // Extract course times—adjust the selector to match your portal's structure Elements courseRows = doc.select("table.course-schedule-table tr"); StringBuilder scheduleText = new StringBuilder(); for (Element row : courseRows) { // Extract specific data (e.g., course name, time, room) String courseName = row.select("td.course-name").text(); String courseTime = row.select("td.course-time").text(); scheduleText.append(courseName).append(" - ").append(courseTime).append("\n\n"); } // Update TextView on the main thread runOnUiThread(() -> { TextView courseTextView = findViewById(R.id.course_text_view); courseTextView.setText(scheduleText.toString()); }); } } }); }
- Never Run Network Calls on Main Thread: Android will throw a
NetworkOnMainThreadException—always use OkHttp'senqueue()(async) or Kotlin Coroutines if you're using Kotlin. - Handle Dynamic Content: If your portal uses JavaScript to load the schedule, Jsoup won't parse it (since it only handles static HTML). In that case, you might need to use a WebView to load the page, wait for JS to render, then extract the HTML from the WebView.
- CSRF Tokens: Many portals require a CSRF token in the login form. You'll need to first fetch the login page, extract the token from the HTML (using Jsoup), then include it in your POST request.
- Error Handling: Add checks for failed responses, missing elements during parsing, and network timeouts to make your app robust.
内容的提问来源于stack exchange,提问作者Nick Adams

