想将目标网址的源代码抓过来,浏览器能够正常访问网页,可是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();
}
}

解决方案 »

  1.   

    应该是代码的问题,比如函数调用方法与传的参数。明显是web服务器500内部错误。
      

  2.   

    这应该是你请求的服务器上的页面出现问题了。
    本身程序没发现问题。
    用http://www.javaeye.com
    测试过了。
      

  3.   

    额,我觉得这应该是服务器故意拒绝吧,我想用Java批量下载一些网页源代码
      

  4.   

    这个程序对于大多数网页都是正常的。
    网页可能为了预防爬虫设置拒绝Java访问,所以我设置成IE浏览器的User-Agent,结果还是失败
      

  5.   

    比如说这个
    http://poj.youdao.com/nanti5/solution/170675/code/
      

  6.   

    使用htmlunit 也有500错误,但可以获取网页内容。
      

  7.   

    这个页面检查用户权限,没有则返回一个500.所以你不能用getinputstream,要用geterrostream。