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

Android WebView无法二次加载同页面问题求助(附代码)

Fixing WebView's Silent Failure on Reopening POST Request Pages

Hey there! Let's break down why your WebView works perfectly the first time but goes completely silent when you reopen the same page. Looking through your code, here are the most likely culprits and actionable fixes:

1. WebView State Isn't Fully Reset Between Loads

Right now you're only clearing the cache with webView.clearCache(true), but WebView holds onto more leftover state than just cache—things like browsing history, cookies, and DOM storage. When you reopen the activity, this old state can interfere with the new load and cause silent failures.

Fix:

Add these thorough cleanup steps right before you call postURL(link, postData); in onCreate:

// Wipe browsing history
webView.clearHistory();
// Clear all stored cookies
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
// Reset DOM storage (disable then re-enable to clear existing data)
webView.getSettings().setDomStorageEnabled(false);
webView.getSettings().setDomStorageEnabled(true);

This ensures every load starts with a fresh, clean WebView instance.

2. loadDataWithBaseURL's History Parameter Causing Conflicts

You're passing null for the final historyUrl parameter in loadDataWithBaseURL. This tells WebView to treat the loaded content as a new history entry, but when you reload the same base URL, WebView might try to reuse old resources instead of fetching fresh content.

Fix:

Use a unique history URL each time—either the actual request URL or add a timestamp to force uniqueness:

// Add a timestamp to avoid reusing old history state
String uniqueHistoryUrl = url + "?t=" + System.currentTimeMillis();
webView.loadDataWithBaseURL(url, htmlString, "text/html", "utf-8", uniqueHistoryUrl);

3. Unmanaged OkHttpClient Requests & Activity Lifecycle Issues

You're creating a new OkHttpClient instance every time the activity loads, which can lead to connection pool bloat. Also, if you reopen the activity before a previous request finishes, the old callback might try to update a destroyed WebView (or vice versa), leading to silent failures.

Fixes:

  • Use a singleton OkHttpClient: Create one instance and reuse it across your app (put this in your VolleyService or a global utility class):
private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build();
  • Cancel pending requests on destroy: Add a global Call variable to track the current request, then cancel it when the activity is destroyed:
private Call currentPostCall; // Declare this at the top of your activity

// In postURL, assign the call to this variable
currentPostCall = OK_HTTP_CLIENT.newCall(request);
currentPostCall.enqueue(new Callback() {
    // ... your existing callback code ...
});

@Override
protected void onDestroy() {
    super.onDestroy();
    // Cancel any pending request to avoid dead callbacks
    if (currentPostCall != null && !currentPostCall.isCanceled()) {
        currentPostCall.cancel();
    }
    // Properly destroy the WebView to free resources
    if (webView != null) {
        webView.destroy();
    }
}

4. Verify Intent Parameters Are Still Valid

Double-check that the link, firstId, etc., values from your Intent aren't null when you reopen the activity. Add a quick log to confirm:

Log.d("WebViewDebug", "Link: " + link + ", First ID: " + firstId);

If any of these are null, your POST data will be invalid, and the page won't load—without throwing an obvious error.

5. Add Error Logging to Catch Silent Failures

Your current onReceivedError method doesn't log anything, so you're missing critical error info. Update it to log errors, and add onReceivedHttpError to catch HTTP status code issues:

@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
    super.onReceivedError(view, request, error);
    Log.e("WebViewError", "Load Error: " + error.getDescription());
}

@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
    super.onReceivedHttpError(view, request, errorResponse);
    Log.e("WebViewHttpError", "HTTP Error Code: " + errorResponse.getStatusCode());
}

This will help you spot issues like expired auth tokens or invalid POST data that might be causing silent failures.

Quick Start Recommendation

Start with fixes 1 and 2—those are the most common reasons for this exact behavior. If those don't work, add the error logging to get more clues about what's going wrong.

内容的提问来源于stack exchange,提问作者yogesh lokhande

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:25:14