Android : Android Web View not intercepting duplicate calls

on Tuesday, September 2, 2014


I have overriden shouldInterceptRequest(WebView view, String url) of WebViewClient to add my custom header because shouldOvverideURL() was not working for the resource loads like images, videos of my web content.


I am returning my own response for the resources.Below is the code



@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
// TODO Auto-generated method stub
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader(SLCFileUtility.TOKEN_HTTP_RESPONSE_HEADER, SLCFileUtility.getToken());
HttpResponse httpReponse = null;
try {
httpReponse = client.execute(httpGet);
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}

// here omit getting content-type and encoding
try {
InputStream reponseInputStream = httpReponse.getEntity().getContent();

String encoding = null;
String contentType = null;
if (httpReponse.getEntity().getContentEncoding() != null) {
encoding = httpReponse.getEntity().getContentEncoding().getValue();
}
if (httpReponse.getEntity().getContentType() != null) {
contentType = httpReponse.getEntity().getContentType().getValue();
if (contentType.equals("text/html") || contentType.equals("application/javascript")) {
logger.info("response is not required for " + httpReponse.toString() + " for the url" + url);
view.clearCache(true);
return null;
}
else {
logger.info("the token in header"
+ httpGet.getHeaders(SLCFileUtility.TOKEN_HTTP_RESPONSE_HEADER)[0].getValue());
logger.info("response " + httpReponse.toString() + " for the url" + url);
view.clearCache(true);
return new WebResourceResponse(contentType, encoding, reponseInputStream);
}
}
else { // for .server files
logger.info("the token in header"
+ httpGet.getHeaders(SLCFileUtility.TOKEN_HTTP_RESPONSE_HEADER)[0].getValue());
logger.info("response " + httpReponse.toString() + " for the url without content type" + url);
view.clearCache(true);
return new WebResourceResponse(contentType, encoding, reponseInputStream);
}

}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
view.clearCache(true);


But when the request is being sent again for the same resource like a video, the method shouldInterceptRequest() is not called. I learnt from here that web view caches the requests from here Intercept and override HTTP-requests from WebView


So i am calling web view clearCache(true) everytime before i leave shouldInterceptRequest(). But still its not working and am not able to add my custom header "token".


cheers, Saurav


0 comments:

Post a Comment