I have written the following java code to download a file from a server that uses http basic authentication. But im getting Http 401 error.I can however download the file by hitting the url directly from the browser.
OutputStream out = null;
InputStream in = null;
URLConnection conn = null;
try {
// Get the URL
URL url = new URL("http://username:password@somehost/protected-area/somefile.doc");
// Open an output stream for the destination file locally
out = new BufferedOutputStream(new FileOutputStream("file.doc"));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
} catch (Exception exception) {
exception.printStackTrace();
}
But,im getting the following exception when i run the program :
java.io.IOException: Server returned HTTP response code: 401 for URL: http://username:password@somehost/protected-area/somefile.doc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at TestDownload.main(TestDownload.java:17)
I am however able to download the file by hitting the url , http://username:password@somehost/protected-area/somefile.doc, directly from the browser.
What could be causing this problem, and any way to fix it ?
Please Help Thank You.