このようにopenConnection()を呼び出す前に、オーセンティケーターを設定します。
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
グローバルデフォルトオーセンティケーターは1つしかないため、複数のユーザーが複数のスレッドでURLFetchを実行している場合、これは実際にはうまく機能しません。その場合は、ApacheHttpClientを使用します。
編集:私は間違っていた。AppEngineはオーセンティケーターを許可していません。許可されている場合でも、グローバルオーセンティケーターインスタンスでマルチスレッドの問題が発生します。スレッドを作成できない場合でも、リクエストは別のスレッドで処理される可能性があります。したがって、この関数を使用してヘッダーを手動で追加するだけです。
import com.google.appengine.repackaged.com.google.common.util.Base64;
/**
* Preemptively set the Authorization header to use Basic Auth.
* @param connection The HTTP connection
* @param username Username
* @param password Password
*/
public static void setBasicAuth(HttpURLConnection connection,
String username, String password) {
StringBuilder buf = new StringBuilder(username);
buf.append(':');
buf.append(password);
byte[] bytes = null;
try {
bytes = buf.toString().getBytes("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
assert false;
}
String header = "Basic " + Base64.encode(bytes);
connection.setRequestProperty("Authorization", header);
}