Android_Basic認証

「Android_Basic認証」の編集履歴(バックアップ)一覧に戻る

Android_Basic認証 - (2013/08/06 (火) 19:52:31) のソース

[[トップページ]] > [[Android]] > BASIC認証

*** WebViewの場合

参考サイト
http://d.hatena.ne.jp/shima111/20120820/p1

WebViewClient()を作成して、onReceivedHttpAuthRequestを設定しておく

     webview = new WebView(this);
     webview.setWebViewClient(new WebViewClient()
     {
         @Override
         public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm)
         {
             System.out.println("onReceivedHttpAuthRequest, host:realm = " + host + ":" + realm);
             handler.proceed("ユーザID", "パスワード");
         }
     });

** URLConnection (HttpURLConnection)の場合

参考サイト
http://others2.blog.so-net.ne.jp/2009-09-09

 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 conn.setRequestProperty("Authorization", "basic "
 	    			  + Base64.encodeToString( ("ユーザID" + ":"  + "パスワード").getBytes() , Base64.DEFAULT));

で出来る。しかし、Android 4.0系では上記でうまくいったものの、Android 2.3系ではうまくいかなかった。
(端末依存?)

別のやり方ではアクセス前に
 				Authenticator.setDefault(new Authenticator() {
 
 					@Override
 					protected PasswordAuthentication getPasswordAuthentication() {
 						return new PasswordAuthentication( "ユーザID" , "パスワード".toCharArray() );
 					}
 		    		  
 				});
を行う。
Android 2.3系でもこの方法ではうまくいった
接続後、念のために解除
 Authenticator.setDefault(null);

2013/8/6