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
It will work for https URL.In this if we are getting Untrusted_cer then we will ignore it
webview.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
@Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
if(error.getPrimaryError()==SslError.SSL_UNTRUSTED){
handler.proceed();
}else{
handler.proceed();
}
}
});
I have no idea about second problem
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<String, String> map = new HashMap<String, String>();
// 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<String,String>)
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, <your map containing the Authorization header>);
return true;
}
});
for handling authorization on your site, just override the following method in your webViewClient and add username and password in its handler.
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
handler.proceed(StringUtils.AUTH_NAME,StringUtils.AUTH_PASS);
}