2014-01-17 38 views
6

您好我想打开这个url http://3864.cloud-matic.net/从我的android webview和我已经尝试了很多方法,但应用程序甚至不打开mainActivity。我试过的是以下。在Android的BasicAuthentication for webview不工作

public void onCreate(Bundle state) { 
    super.onCreate(state); 
    setContentView(R.layout.main); 
    WebView webView = (WebView) findViewById(R.id.webView1); 
    webView.setHttpAuthUsernamePassword("cloud-matic.net/",  "realm", username, password); 
    webView.loadUrl("http://3864.cloud-matic.net/"); 
} 

请给我想法我错了。 阿里

+0

“应用程序甚至不打开mainActivity”你会得到某种错误或崩溃或只是一个空白的屏幕? – hypd09

+0

你能提供一个logcat吗? – PsyGik

+0

首先,我需要问什么是“realm”,它在setHttpAuthUsernamePassword函数中使用。如果我在共享logcat之前缺少一些值,那么? – Ali

回答

20
webview.setWebViewClient(new MyWebViewClient()); 

private class MyWebViewClient extends WebViewClient { 
    @Override 
    public void onReceivedHttpAuthRequest(WebView view, 
      HttpAuthHandler handler, String host, String realm) { 
     handler.proceed("[email protected]", "mypassword"); 
    } 
} 

这是最投票的解决方案有我不知道哪里来的URL设置为open.Please建议。

+0

你试过添加'webView.loadUrl(“http://3864.cloud-matic .net /“);'设置网络视图客户端后? –

+0

嗨,是的,我正在使用我的onCreate方法。 webView.loadUrl( “http://3864.cloud-matic.net/”); webView.setWebViewClient(new MyWebViewClient()); – Ali

+0

你需要在调用'loadUrl'时提供'http://'的URL,即'webView.loadUrl(“http://3864.cloud-matic.net”);' –

0

这应该是完美的代码片段。

webView.getSettings().setJavaScriptEnabled(true); 
    webView.setFocusable(true); 
    webView.loadUrl("http://3864.cloud-matic.net/"); 
    webView.setWebViewClient(new WebViewClient() { 

     @Override 
     public void onReceivedHttpAuthRequest(WebView view, 
               HttpAuthHandler handler, String host, String realm) { 
      handler.proceed("[email protected]", "mypassword"); 
     } 

     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      view.loadUrl(url); 
      return true; 
     } 

     @Override 
     public void onPageStarted(WebView view, String url, Bitmap favicon) { 
      super.onPageStarted(view, url, favicon); 
      prDialog.setMessage("Please wait ..."); 
      prDialog.show(); 
     } 

     @Override 
     public void onPageFinished(WebView view, String url) { 
      super.onPageFinished(view, url); 
      if (prDialog != null) { 
       prDialog.dismiss(); 
      } 
     } 
    }); 
0

根据另一个话题的答案,我以一种不同的方式做出了答案。

此解决方案也适用于以下情况:显示自动登录表单,验证失败时(在这种情况下,重写'onReceivedHttpAuthRequest'的解决方案不起作用,因为您正在获取正常的html页面而没有错误)。

String up = "yourusername"+":"+"yoursuperstrongpassword"; 
String authEncoded = new String(Base64.encodeBase64(up.getBytes())); 
String authHeader = "Basic "+authEncoded; 
Map<String, String> headers = new HashMap<>(); 
headers.put("Authorization", authHeader); 
myWebView.loadUrl("https://192.168.137.1:8443/tmedserver/doctor/doctorConsultations/consultationCall.mvc?consultationId=23", headers);