Why WebResourceResponse return null in shouldInterceptRequest()? - android

I'm trying to get a POST response of a request in WebView. Here are my codes.
mWebview.setWebViewClient(new WebViewClient() {
#Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
WebResourceResponse w = super.shouldInterceptRequest(view, url);
Log.i("type", w.getMimeType());
return super.shouldInterceptRequest(view, url);
}
});
But the program crashes and the error is w is null. Could anyone tell me why is that or give me any solution to get a POST response of a request in WebView?
Thank you.

shouldInterceptRequest() return null, means that no one intercept the request, and the webview will load the origin URL.
if you want to intercept the request, you should make your own WebResourceResponse with the information from the URL param.

In the documentation, it states that "If the return value is null, the WebView will continue to load the resource as usual.". In the case that something should intercept the request, the response is returned by the override method.
https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView, android.webkit.WebResourceRequest)

Related

How to block ads using WebResourceResponse shouldInterceptRequest

I usualy use shouldOverrideUrlLoading to block ads in webview, but this time, the ads links in a new website doesn't captured in
public boolean shouldOverrideUrlLoading(WebView view, String url)
and
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
but it captured in
public WebResourceResponse shouldInterceptRequest(final WebView view, String url)
so, i used this method
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
Log.d("soidfzs", url);
WebResourceResponse webResourceResponse = null;
if (url.contains("https://googleads") || url.contains("doubleclick") || url.contains("google-analytics.com") || url.contains("adservice") || url.contains("securepubads")) {
Log.d("soidfzs", "here");
return webResourceResponse;
} else {
return super.shouldInterceptRequest(view, url);
}
}
but, links still loading and ads showing
So, what should i return ?
You are returning webResourceResponse which you set to null prior to your if statement where you check whether the request might be for an ad.
The documentation for shouldInterceptRequest however states:
* #return A {#link android.webkit.WebResourceResponse} containing the
* response information or {#code null} if the WebView should load the
* resource itself.
So in returning null, you are telling the WebViewClient to load the resource itself, i.e., fulfil the ad request and load the ad.
In order to let the request slide and return your own value, you have to return your own WebResourceResponse instance which must not be null for this to work.
return new WebResourceResponse(
"text/html",
"UTF-8",
null
);
Here, I set the mimeType (first argument) to "text/html", although it could probably also be something else, like "text/plain".
I set the second argument—encoding—to "UTF-8"(same as before: could probably be something else).
And now for the most important part: I set data, the third argument, to null.
This results in the WebView getting a valid WebResourceResponse instance which is not null but has no data which in turn results in nothing loading.
Be aware that this will trigger WebViewClient#onReceivedError as the WebView client essentially couldn’t load anything. This is not a problem per se, but something to look out for in case you override onReceivedError.

Getting callback data from WebView Android

I am using a webview to submit a form and redirect. When the form is submitted successfully it will print a json response to the console.
My question is how can I get the jsonData String from the client?
chromium: [INFO:CONSOLE(1)] "Callback....jsonData, etc"
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Insert your code here
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
You could extend the WebViewClient class and create a method to intercept the POST request made from clicking the form post button in the HTML in your WebView. Then, make the HTTP POST request in the code, rather than in the WebView and parse the results anyway you wish, then refresh the WebView any way you wish at the end of it all. There is an example of doing so here:
https://github.com/KeejOow/android-post-webview/blob/master/PostWebview/postwebview/src/main/java/com/solidsoftware/postwebview/InterceptingWebViewClient.java

Intercept Form POST request in WebView

I'm trying to add authorization headers in every request in WebView. I can override shouldOverrideUrlLoading method for GET request, but I can't get POST request to work. I have tried many answer from this site, and none of them works. Is there a proper way to do this?
Edit:
For GET Request I use:
webView.setWebViewClient(new WebViewClient() {
#Override
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString(), getHeader());
return true;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url, getHeader());
return true;
}
}
I used WebViewClient.shouldInterceptRequest() to intercept POST request. But somehow the request I create became GET.

android webview custom headers not going out on page resource requests

In my android app I am connecting to a secure site where my login credentials are contained in custom headers. I am able to log in successfully because the custom headers are sent with the new page request.
Based on my custom header information there is specific page functionality which is enabled for my device. The problem is that when I load resources from the home page after login the custom headers that I specify in the webview.LoadUrl(); are not sent. So the end result is that I can log in but do not receive the special functionality that is associated with my device.
I have tried both of these overrides. shouldOverrideUrlLoading seems to work when changing URL's but shouldInterceptRequest does not seem to get called on resource requests? If it is my implementation does not work?
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
request.getRequestHeaders().putAll(getExtraHeaders());
return super.shouldInterceptRequest(view, request);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url, getExtraHeaders());
return false;
}
See if this works a little better for you:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.post(new Runnable() {
#Override
public void run() {
view.loadUrl(url, getExtraHeaders());
}
});
// true means: yes, we are overriding the loading of this url
return true;
}
This additional code is just a suggestion/outline and should not be taken as cut/paste ready code
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String mimetype;
String encoding;
Map<String, String> headers = new HashMap<>();
headers.putAll(request.getRequestHeaders());
headers.putAll(getExtraHeaders());
URL url = request.getUrl().toString();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
for (String key : headers.keySet()) {
conn.setRequestProperty(k, headers.get(k));
// TODO look for the mimetype and encoding header information and set mimetype and encoding
}
return new WebResourceResponse(mimetype, encoding, conn.getInputStream());
// return null here if you decide to let the webview load the resource
}
Maybe try a different approach, store whatever your need in a cookie for your host using WebKit's CookieManager and use the request's cookie header instead of your custom headers

How to get server response code for redirecting response on WebView

I have a WebView component, I have set a WebViewClient to it:
WebView webView = (WebView)findViewById(R.id.my_webview);
webView.setWebViewClient(
new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String newUrl) {
//Here, I handle the url redirecting.
//#newUrl is the redirected url
// How to get server response code here??
}
}
);
As you see above, my code handles redirecting url in shouldOverrideUrlLoading(...). It works fine. Sometimes, the redirected server response is an error code with error message, e.g. the server log is:
< 400
< Content-Type: text/plain
Bad header value: 'name'
In above case, the WebView page shows "Bad header value: 'name'".
My question is, in my java code, how can I get the server response code (e.g. in above case 400) of the redirecting response?
==================== What I tried ==========================
I tried to add onReceivedError() into new WebViewClient(){...}, to catch the error response, but the code does not get executed.
#Override
public void onReceivedError (WebView view, int errorCode, String description, String failingUrl){
Log.v("onReceivedError:", errorCode+":"+description);
}
As of now.. the only (proper) way i guess is not through java code.Infact,it is by injecting javascript into your webview which inturn would give you the response code.
See this answer here

Categories

Resources