java - 如何在 Java 中防止 403 HTTP 错误代码?

标签 java http http-headers

我使用简单代码获取 http://www.ip-adress.com 的 html ,但它显示错误 http 代码 403。 我在程序中的 google.com 等其他网站上尝试过,它可以工作。 www.ip-adress.com在浏览器中也能打开,为什么在java程序中不能使用。

 public class urlconnection
{
  public static void main(String[] args)
 {
    StringBuffer document = new StringBuffer();
    try 
    {
        URL url = new URL("http://www.ip-adress.com");
        URLConnection conn = url.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null)
        document.append(line + " ");
        reader.close();
    }
    catch (MalformedURLException e) 
    {
        e.printStackTrace(); 
    }
    catch (IOException e)
    {
        e.printStackTrace(); 
    }
    System.out.println(document.toString());
}
}



java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.ip-adress.com/

at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at urlconnection.main(urlconnection.java:14)

最佳答案

这是你需要的行

conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

引用this

关于java - 如何在 Java 中防止 403 HTTP 错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13679869/

相关文章:

java - failed.org.hibernate.exception.JDBCConnectionException : Error calling Driver#connect with PostGres Hibernate

java - maven项目执行失败 "maven-thrift-plugin"

http-headers - 缓存控制最大年龄元标记未注册

java - 如何向 OkHttp 请求拦截器添加 header ?

java - 使用 Spring 加载显示 NPE 的 java 属性文件

java - 第一次如何使用 eclipse 设置 SQLite?

java - 编写一个简单的 HTTP 服务器来接受 GET 请求

c# - 在 ServiceStack 中使用 IRestClient 发出 HEAD 请求

http - 无法从 http 端点消费

javascript - 使用带有自定义 header 的 Ajax 加载图像