I have a webview to which I want to add custom headers, I want this to cater for redirects and looking at how to do it, I stumbled at the highest voted answer here.
However this solution is using a now deprecated approach. I tried to modify the solution:
public void webViewUrlConn() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("https://someUrl.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(url.getHost());
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Cookie", cookie);
urlConnection.setRequestProperty("CRM_USER_AGENT", "crm_app");
urlConnection.setRequestMethod("POST");
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
data = new java.util.Scanner(in).useDelimiter("\\A").next();
System.out.println("Data:" + data);
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
wv.loadData(data, "text/html", "UTF-8");
pd.setVisibility(View.INVISIBLE);
wv.setVisibility(View.VISIBLE);
}
});
}
}).start();
}
This works flawless. But this is not what I need. I wanted to override the WebViewClient class to cater for even the links clicked on the webview, I came up with the following:
WebViewClient webViewClient = new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url1) {
try {
URL url = new URL(url1);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(url.getHost());
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Cookie", cookie);
urlConnection.setRequestProperty("CRM_USER_AGENT", "crm_app");
urlConnection.setRequestMethod("POST");
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
data = new java.util.Scanner(in).useDelimiter("\\A").next();
System.out.println("Data:" + data);
urlConnection.getContentType();
urlConnection.getContentEncoding();
urlConnection.getContentEncoding();
urlConnection.disconnect();
return new WebResourceResponse("text/html","UTF-8", in);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
wv.setWebViewClient(webViewClient);
pd.setVisibility(View.INVISIBLE);
wv.setVisibility(View.VISIBLE);
wv.loadUrl("https://someurl.com");
The above does not work and I cannot establish why - I get a blank webview. and when I print the value from data
I get some unknown characters.