本文介绍了如何防止Java中出现403 HTTP错误代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用简单的代码获取 http://www.ip-adress.com 的html,但显示错误http代码403.我在其他网站(例如google.com)中尝试了该程序,它可以工作.我也可以在浏览器中打开www.ip-adress.com,为什么不能在Java程序中使用它.
I use simple code to get html for http://www.ip-adress.com, but it shows error http code 403.I try it in other website like google.com in program, it can work. i can also open www.ip-adress.com in browse, why i can't use it in java program.
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");
引用此
这篇关于如何防止Java中出现403 HTTP错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!