我正在尝试阅读http://www.meuhumor.com.br/在java上使用这个:
URL url;
HttpURLConnection connection = null;
try{
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
dataout.flush();
dataout.close();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null){
response.append(line);
response.append('\n');
}
br.close();
String html = response.toString();
我可以使用任何浏览器访问该网站,但是当我尝试使用 Java 获取 html 时,我收到 java.io.IOException: Server returned HTTP response code: 403 for URL:
有人知道获取 html 的方法吗?
最佳答案
您很可能会收到 HTTP 403 响应,因为您的 POST
请求没有正文。您的代码看起来像是正在尝试提交表单。如果您的目的是简单地下拉页面内容而不提交表单,请尝试 GET
请求,删除 Content-Type
header ,删除 connection.setDoOutput(true)
,并删除 3 个 DataOutputStream
行。
关于java - 为什么我在 java 上读取网站 url 时出现 403 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12065099/