12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java の URLConnection で基本認証を行う際のハマりどころ

Posted at

基本認証はサーバ側が対応していれば、以下のような URL でアクセス可能です(以下 URL は記事用のダミーです)。

http://username:password@example.com

以下のように curl で叩くと期待した結果が帰ってきます。

$ curl http://username:password@example.com

これを Java の URLConnection で行うと失敗します。

URL url = new URL("http://username:password@example.com");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();  // ここで失敗する

Android では以下のような例外が出ます。

java.io.FileNotFoundException: http://username:password@example.com
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250)
     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
     at com.example.ogata.Test$1.run(Test.java:53)

Java では以下のような例外が出ます。

java.io.IOException: Server returned HTTP response code: 401 for URL: http://username:password@example.com
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
	at Test$1.run(Test.java:31)

Java では URLConnection を用いた基本認証は以下のように行います。

URL url = new URL("http://example.com");
URLConnection conn = url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString("username:password".getBytes(), Base64.NO_WRAP));
// conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString("username:password".getBytes()));
InputStream is = conn.getInputStream();

Base64 の API は Android と Java 8 で若干異なります。上記のコメントアウトされている行は Java 8 です。

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?