2
我已經編寫了以下java代碼以便從使用http基本身份驗證的服務器下載文件。但我得到HTTP 401錯誤。 然而,我可以通過直接從瀏覽器中點擊網址來下載文件。從我的java代碼中使用基本http身份驗證的服務器下載文件的問題
OutputStream out = null;
InputStream in = null;
URLConnection conn = null;
try {
// Get the URL
URL url = new URL("http://username:[email protected]/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();
}
但是,即時得到以下異常:當運行程序:
java.io.IOException: Server returned HTTP response code: 401 for URL: http://username:[email protected]/protected-area/somefile.doc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at TestDownload.main(TestDownload.java:17)
不過,我可以通過點擊網址,http://username:[email protected]/protected-area/somefile.doc從瀏覽器下載文件,直接。
什麼可能導致這個問題,以及以任何方式解決它?請致電 謝謝。