Android_Basic認証

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

WebViewの場合



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)の場合



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
最終更新:2013年08月06日 19:52