Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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


以下のように 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 です。

Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away


No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
Help us understand the problem. What is going on with this article?