Android: Intercept AJAX call from WebView

前端 未结 3 1413
傲寒
傲寒 2020-12-05 11:41

I want a HTML/javascript application, running in a WebView to make AJAX calls that are handled by the Java code.
Idea

3条回答
  •  失恋的感觉
    2020-12-05 11:50

    Good news everyone: With API level 11, they put in the shouldInterceptRequest method into the WebViewClient class. It also fires on requests the application inside the WebView triggers. You can override it as follows:

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url)
    {
        if (magicallyMatch(url))
            return new WebResourceResponse("application/json", "utf-8", magicallyGetSomeInputStream());
    
        return null;
    }
    

    From the Android Reference:

    public WebResourceResponse shouldInterceptRequest (WebView view, String url)

    Since: API Level 11

    Notify the host application of a resource request and allow the application to return the data. If the return value is null, the WebView will continue to load the resource as usual. Otherwise, the return response and data will be used. NOTE: This method is called by the network thread so clients should exercise caution when accessing private data.

    Parameters

    view The WebView that is requesting the resource.

    url The raw url of the resource.

    Returns

    A WebResourceResponse containing the response information or null if the WebView should load the resource itself.

    Also check WebResourceResponse.

    Hope this helps.

提交回复
热议问题