You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现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.

1. Set Up Permissions & Dependencies

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.xml right 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 the dependencies block (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'
    
2. Implement Background Login to the Student Portal

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 with name attributes like username, password, or maybe student_id).
  • Persist cookies to maintain your logged-in session (OkHttp's CookieJar handles 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());
        }
    }
});
3. Scrape Specific Course Data (e.g., Upcoming Class Times)

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 unique class or id (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());
                });
            }
        }
    });
}
4. Key Notes to Avoid Headaches
  • Never Run Network Calls on Main Thread: Android will throw a NetworkOnMainThreadException—always use OkHttp's enqueue() (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:32:37