Skip to content

Instantly share code, notes, and snippets.

@xtools-at
Last active February 13, 2023 04:44
Show Gist options
  • Save xtools-at/cf3eb1654d1162ef9a93c5354154344c to your computer and use it in GitHub Desktop.
Save xtools-at/cf3eb1654d1162ef9a93c5354154344c to your computer and use it in GitHub Desktop.
Force Android WebView to load Ressources via HTTPS
package at.xtools.httpswebviewexample;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.net.URL;
import java.net.URLConnection;
public class HttpsWebViewExample extends AppCompatActivity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
webView = (WebView) findViewById(R.id.exampleWebViewIdInYourLayoutXml);
webView.setWebViewClient(new WebViewClient() {
//custom settings
//...
///Here it starts to get interesting!
//Intercept WebView Requests for Android API < 21
@Deprecated
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (url.startsWith("http://")) {
try {
//change protocol of url string
url = url.replace("http://","https://");
//return modified response
URL httpsUrl = new URL(url);
URLConnection connection = httpsUrl.openConnection();
return new WebResourceResponse(connection.getContentType(), connection.getContentEncoding(), connection.getInputStream());
} catch (Exception e) {
//an error occurred
}
}
return super.shouldInterceptRequest(view, url);
}
//Intercept WebView Requests for Android API >= 21
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.startsWith("http://")) {
try {
//change protocol of url string
url = url.replace("http://","https://");
//return modified response
URL httpsUrl = new URL(url);
URLConnection connection = httpsUrl.openConnection();
return new WebResourceResponse(connection.getContentType(), connection.getContentEncoding(), connection.getInputStream());
} catch (Exception e) {
//an error occurred
}
}
return super.shouldInterceptRequest(view, request);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment