Java中出现401错误时如何下载文件
我想使用Java从Internet下载文件,但我的程序有时会显示401错误,但我无法获取它。
有趣的是,当我将这个文件的链接放在 HTML 网站上时,我可以通过单击右键并“另存为”来下载它。
在Java中我该怎么做才能达到同样的效果?
I would like to download a file from the Internet using Java, but from time to time my program shows 401 error and I cannot get it.
What is interesting when I put link to this file on HTML website, I can download it by clicking right click and "Save as".
What can I do to achieve the same effect in Java ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查浏览器实际发送的内容,尤其是标头,并确保您执行相同的操作。 Cookie、身份验证和引用字段可能很有趣。
由于您未经授权,因此可能需要首先使用 java 访问该网站并确保您获得会话 cookie(如果适用)。
甚至可能是对 html 页面的访问使服务器允许下载一段时间,或者每个时间单位的下载数量受到限制。在最后一种情况下,你无能为力。
Check what the browser actually sends, especially the headers, and make sure you do the same. Cookies, authenticated and referre fields may be interesting.
As you got an unauthorized it may be necessary to go to the website first with java and ensure you get your session cookie (if applicable).
It could even be that access to the html page makes the server allow downloads for some time, or that the number of dowloads per time unit is limited. In the last case there's nothing you can do.
来自维基百科:
显然,您的 Java 代码没有处理一些与身份验证相关的问题,或者浏览器可以处理一些与服务器相关的问题。为了让我们能够为您提供更多帮助,您需要:
向我们提供您代码的相关部分。
向我们提供有关您的链接的信息。如果链接不引用简单的静态内容,则大约有一百万种不同的情况可能会出错。
需要注意的一些事项:
使用网络嗅探器(例如Wireshark)找出两者之间的区别Java 和浏览器会话。
打印出 Java 代码接收和发送的所有标头,并与网络嗅探器或 实时 Http 标头 显示。
您的代码是否正确处理任何身份验证 cookie?
如果您已经从浏览器访问了该链接,您的 Java 代码是否可以正常工作?
From Wikipedia:
Apparently there is some authentication-related issue that your Java code does not deal with - or some server-related issue that the browser does deal with. For us to be able to help you more you need to:
Provide us with the relevant parts of your code.
Provide us with information on your link. If the link does not refer to simple static content there are about a million different things that could go wrong.
Some things to look for:
Use a network sniffer (e.g. Wireshark) to find out what is different between the Java and browser sessions.
Print out all headers received and sent by the Java code, and compare to what the network sniffer or Live Http Headers shows.
Is your code handling any authentication cookies correctly?
Does your Java code work fine if you have already accessed the link from a browser?