2014-01-17 51 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);