Java Http(s)URLConnection java.io.IOException : Server returned HTTP response code: 403

标签 java tomcat7 wget

java.io.IOException:服务器返回 HTTP 响应代码:403 为 http://www.budgetbottle.com/vivino.xml

当在本地 tomcat 服务器上通过 Java 类 main 方法运行时,此 URL 有效(返回内容),但在生产计算机上的 tomcat 服务器上运行时,它会抛出错误。

代码如下:

URL url = new URL("http://www.budgetbottle.com/vivino.xml");    
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
// System.setProperty("http.agent", "");
System.setProperty("http.agent", "Chrome");

// urlcons.setRequestProperty("Content-Language", "en-US");
// urlcons.setUseCaches(false);
// urlcons.setDoInput(true);
// urlcons.setDoOutput(true);

我已经应用了针对此论坛上提出的类似问题提供的解决方案,但没有解决方案有效。

更新:
我刚刚注意到,wget 实用程序也会在生产系统上引发相同的错误,而在本地系统上则没有问题。请注意使用User-Agent等选项

这是系统特定错误吗?

最佳答案

我使用了下面的代码,它对我来说效果很好。您的服务器上是否有某种速率限制或 IP 禁止系统,可能会阻止您的连接?

    URL url = new URL("http://www.budgetbottle.com/vivino.xml");
    HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
    urlcon.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
    System.setProperty("http.agent", "Chrome");
    BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    System.out.println(sb.toString());

关于Java Http(s)URLConnection java.io.IOException : Server returned HTTP response code: 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50258583/

相关文章:

java - 在不知道公共(public)类名的情况下编译 .java 文件

java - 如何快速采集 "contains"执行计划?

mysql - liferay使用mysql时出现错误

bash - 使用 url 重定向下载文件

php - 我如何通过 linux 邮件命令通过电子邮件发送 wget 下载的结果?

java - 从在 32 位 jre 上运行的桌面应用程序内部使用 64 位 jre 调用第 3 方 API?是否可以?

java - Jersey Rest Web 服务返回对象列表,其中对象包含文件的字节数组

java - 更改 Eclipse 中的默认动态 Web 模块版本

java - 放弃连接警告 - tomcat 7 抛出 PooledConnection 异常

linux - 下载站点上的所有 mp3 文件并在此过程中重命名它们