2011-01-08 89 views
32

当我从一个网址提取数据与403响应HttpURLConnection类的403错误阅读响应内容

is = conn.getInputStream(); 

它抛出IOException,我无法获得响应数据。

但是当我使用Firefox和直接访问URL时,ResponseCode仍然是403,但我可以得到的HTML内容

回答

53

HttpURLConnection.getErrorStream方法将返回可用于检索从错误状况数据的InputStream(如404),根据javadocs。

+3

不,它不会,因为函数的代码只包含'return null;'线。 (Java 6,7) – Gangnus 2014-03-25 13:56:38

+2

@Gangnus仔细阅读Javadoc:“如果连接没有连接,或者如果服务器在连接时没有错误,或者如果服务器发生错误但没有发送错误数据,则此方法将返回null,这是默认值。“ 否则(错误4xx),您将获得要读取的流。 – 2014-06-05 09:20:32

+0

@MiljenMikic代码和Javadoc之间的区别只意味着最后一个是错误的。 – Gangnus 2014-06-05 11:43:56

10

尝试这样:

try { 
    String text = "url"; 
    URL url = new URL(text); 
    URLConnection conn = url.openConnection(); 
    // fake request coming from browser 
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;  rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); 
    String f = in.readLine(); 
    in.close(); 
    System.out.println(f); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
16

HttpURLConnection用例:

String response = null; 
try { 
    URL url = new URL("http://google.com/pagedoesnotexist"); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 

    // Hack to force HttpURLConnection to run the request 
    // Otherwise getErrorStream always returns null 
    connection.getResponseCode(); 
    InputStream stream = connection.getErrorStream(); 
    if (stream == null) { 
     stream = connection.getInputStream(); 
    } 
    // This is a try with resources, Java 7+ only 
    // If you use Java 6 or less, use a finally block instead 
    try (Scanner scanner = new Scanner(stream)) { 
     scanner.useDelimiter("\\Z"); 
     response = scanner.next(); 
    } 
} catch (MalformedURLException e) { 
    // Replace this with your exception handling 
    e.printStackTrace(); 
} catch (IOException e) { 
    // Replace this with your exception handling 
    e.printStackTrace(); 
} 
0

即使在添加代理程序字符串后,我也收到了相同的错误。最后经过数天调查发现问题。如果url方案以“HTTPS”开头,会导致错误403,这真的很糟糕。它应该是小写(“https”)。因此,请确保在打开连接之前调用“url.toLowercase()”。