以下の内容はhttps://unageanu.hatenablog.com/entry/20090820/1250772013より取得しました。


URLフェッチ機能でBasic認証を使う

Google App EngineのURLフェッチ機能では、HttpURLConnectionが普通に使える訳ですが、Basic認証が必要なサイトにアクセスしたいと思って以下のように書いてデプロイしたら実行時エラーに

static {
    Authenticator.setDefault( new Authenticator(){
        @Override
        protected  PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication( USER, PASS.toCharArray() );
        }
    });
}

発生したエラーは次の通り。

Caused by: java.security.AccessControlException: access denied (java.net.NetPermission setDefaultAuthenticator)
	at java.security.AccessControlContext.checkPermission(Unknown Source)
	at java.security.AccessController.checkPermission(Unknown Source)

なるほど。まぁ、許可されないだろうな、常識的に考えて。

対策

ということで自前でAuthorizationヘッダを付与して対処。Base64エンコーダはApp Engineのライブラリにあったものを使用してみました。

import com.google.appengine.repackaged.com.google.common.util.Base64;
...
connection.addRequestProperty("Authorization",  "Basic " + encodeBase64( USER + ":" + PASS ));
...
String encodeBase64( String str ) {
    try {
        return Base64.encode( str.getBytes("UTF-8") );
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e); // 起こりえない
    }
}

これで無事目的のサイトにアクセスできることを確認。よしよし。




以上の内容はhttps://unageanu.hatenablog.com/entry/20090820/1250772013より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14