我使用简单代码获取 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/