I have researched and researched and researched this until I\'ve gone grey and bald. How on earth do I get a webview to work for a site that needs http basic authentication over
This simple example abuses a page on HttpWatch since it's more fun with a working public example.
The resource in question, https://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx?randomgarbage
uses basic auth over HTTPS and can be loaded without authentication failure like this (tested using Android 2.3.7):
WebView v = ...; // Your webview goes here.
try {
HashMap map = new HashMap();
// This test service takes the username "httpwatch" and a random
// password. Repeating a password can lead to failure, so we create
// a decently random one using UUID.
String usernameRandomPassword = "httpwatch:" + UUID.randomUUID().toString();
String authorization = "Basic " + Base64.encodeToString(usernameRandomPassword.getBytes("UTF-8"), Base64.NO_WRAP);
map.put("Authorization", authorization);
v.loadUrl("https://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx?" + System.currentTimeMillis(), map);
} catch (UnsupportedEncodingException e) {}
This works on ICS and Gingerbread. Don't have access to anything older than that, but loadUrl(String, Map
was introduced in API level 8, so I don't see why it shouldn't work for that to.
Clarification for Nappy:
To support authentication for subsequent requests you supply a WebViewClient
and do the following:
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url, );
return true;
}
});