浏览器能访问 Java却返回Http500

wd9053 wd9053 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
想将目标网址的源代码抓过来,浏览器能够正常访问网页,可是Java连接却报错:
Exception in thread "main" java.io.IOException: Server returned HTTP response co
de: 500 for URL:
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown So
urce)
at Test.main(Test.java:21)
上网搜了一下,然后设置了User-Agent,可是结果不变。
User-Agent的值是ieHttpHeaders获取的,IE能够正常访问页面。

import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;

public class Test
{
public static void main(String[] args) throws Exception
{
URL u = new URL("网址");
HttpURLConnection con = (HttpURLConnection)u.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C)");
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("test.html"));
byte[] arr = new byte[512];
int temp;
while((temp = bis.read(arr, 0, 512)) != -1)
{
bos.write(arr, 0, temp);
}
bos.flush();
bos.close();
bis.close();
}
}
...全文

相关推荐

评论 13
收藏 已收藏
分享
返回顶部
wd9053
Java SE 62,621 成员 307,251 内容