6

Is there any way to intercept redirect requests in Android WebView? shouldInterceptRequest(WebView,WebResourceRequest) does not seem to get called!

I wanted to automatically catch token expiration in all web view requests by:

  1. Issuing a redirect rather than a 401 from the server
  2. Using shouldOverrideUrlLoading() to invoke AppAuth where a login is necessary
  3. Using shouldInterceptRequest to bounce back to the original URL with a refreshed token where a login is not necessary

Item 2 is working fine, but item 3 is failing spectacularly since shouldInterceptRequest seems not to be called for redirects, which seems really wrong -- particularly since this is not documented and the WebResourceRequest API would lead one to believe that one can even check whether the request is a redirect.

I'd happily respond to 401's instead of using redirects -- but I see no way to retry the request "in situ" with an updated token, unless the request happens to be a top-level page request.

I suppose I could try the old "in page" redirect instead of a 302 to see if that works any better, but even if it does that is really a hack.

(Note that this is clearly a different issue than Android WebView, how to handle redirects in app instead of opening a browser -- as I already have a webview and am trying to intercept and manipulate redirection requests.)

Jess Holle
  • 633
  • 5
  • 15
  • Hey! Maybe it can help you https://stackoverflow.com/questions/4066438/android-webview-how-to-handle-redirects-in-app-instead-of-opening-a-browser – Franklin Hirata Aug 25 '17 at 19:56
  • No, I need to let the existing web view handle the results of the request, including for non-top-level requests, e.g. for tags, etc. In cases I need to refashion the request, though. It seems this is simply not a workable approach with WebViewClient as it stands. – Jess Holle Aug 26 '17 at 20:17
  • @JessHolle did you got any solution for this, would be really helpful if u can share. – Jaber Shabeek Feb 20 '19 at 08:16

1 Answers1

0

Example of interception on Kotlin:

webView.webViewClient = object: WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        if (url.startsWith("https://example.com")) {
            // ...
            return false
        }
        return super.shouldOverrideUrlLoading(view, url)
    }
}
Pavel Shorokhov
  • 4,485
  • 1
  • 35
  • 44