Basic authentication can be accessed with the following URL if the server side supports it (the URL below is a dummy for articles).
http://username:[email protected]
If you hit it with curl as below, you will get the expected result.
$ curl http://username:[email protected]
Doing this with a Java URLConnection will fail.
URL url = new URL("http://username:[email protected]");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream(); //Fail here
On Android, I get the following exception.
java.io.FileNotFoundException: http://username:[email protected]
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)
In Java, I get the following exception:
java.io.IOException: Server returned HTTP response code: 401 for URL: http://username:[email protected]
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)
In Java, basic authentication using URLConnection is performed as follows.
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();
The Base64 API is slightly different for Android and Java 8. The commented out line above is Java 8.