从我的 java 代码使用基本 http 身份验证的服务器下载文件时出现问题
我编写了以下 java 代码来从使用 http 基本身份验证的服务器下载文件。但我收到 Http 401 错误。但是,我可以通过直接从浏览器点击 URL 来下载该文件。
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();
}
但是,当我运行程序时,我收到以下异常:
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)
但是我可以下载该文件通过点击 url ,http://username:password@somehost/protected-area/somefile。 doc,直接来自浏览器。
可能是什么原因导致这个问题,以及有什么方法可以解决它?
请帮忙 谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我正在使用 org.apache.http:
等...
I'm using org.apache.http:
etc...