从 java.io.IOException 中提取 HTTP 状态码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37302615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:23:35  来源:igfitidea点击:

Extract HTTP Status Code from java.io.IOException

javahttpioexceptionhttp-status-codes

提问by Yakov

How is it possible (if at all) to get the HTTP status code from a java.io.IOException in java ?

怎么可能(如果有的话)从java.io.IOException in java ?

回答by CherryDT

I'm assuming this is about an IOExceptionthrown by a URLConnection.

我假设这是关于 aIOException抛出的URLConnection

Three possibilities to handle this, depending on your restrictions.

处理此问题的三种可能性,具体取决于您的限制。

1) Cast your URLConnectionto a HttpURLConnectionand call getResponseCode

1) 投你URLConnection到 aHttpURLConnection并打电话getResponseCode

If you have access to the connection object, you can get the status code using this code:

如果您有权访问连接对象,则可以使用以下代码获取状态代码:

int statusCode = (HttpURLConnection)theConnection).getResponseCode();

2) Use a HttpURLConnectioninstead of an URLConnectionin the first place

2)使用HttpURLConnection,而不是URLConnection在第一位

If you can do this, it would be the best solution, because an URLConnectiondoesn't throw on error status codes. You can just call getResponseCodeand check the status without getting any exception first.

如果你能做到这一点,这将是最好的解决方案,因为 anURLConnection不会抛出错误状态代码。您可以先调用getResponseCode并检查状态而不会出现任何异常。

3) Parse the exception message itself

3)解析异常消息本身

The IOException's message usually looks like this:

IOException的消息通常是这样的:

Server returned HTTP response code: 403 for URL: http://something

So you can just use a regex (or simple string manipulation) to get the response code out of there.

所以你可以只使用正则表达式(或简单的字符串操作)来获取响应代码。

Note that for status 404, the message doesn't look like this and a FileNotFoundExceptionis thrown. I'm not sure if there are any other status codes throwing "special" exceptions like this, but watch out for this.

请注意,对于状态 404,消息看起来不是这样,并且FileNotFoundException抛出了 a 。我不确定是否有任何其他状态代码会抛出这样的“特殊”异常,但要注意这一点。

Example code demonstrating methods 2 & 3:

演示方法 2 和 3 的示例代码:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class HelloWorld {
    public static void testUrl(String urlString) throws MalformedURLException {
        URLConnection conn = null;
        System.out.println("Testing URL " + urlString);
        try {
            URL url = new URL(urlString);
            conn = url.openConnection();

            // Just to make the exception happen
            conn.getInputStream();

            System.out.println("Success!");
        } catch(IOException ex) {
            System.out.println("Error!");
            System.out.println();

            // Method 2 with access to the URLConnection object
            // (Method 1 would have been having the connection as HttpURLConnection from the beginning.)
            int responseCode = 0;
            System.out.println("Trying method 2 to get status code");

            try {
                if(conn != null) {
                    // Casting to HttpURLConnection allows calling getResponseCode
                    responseCode = ((HttpURLConnection)conn).getResponseCode();
                } else {
                    System.out.println("conn variable not set");
                }
            } catch(IOException ex2) {
                System.out.println("getResponseCode threw: " + ex2);
            }

            System.out.println("Status code from calling getResponseCode: " + responseCode);
            System.out.println();

            // Method 3 without access to the URLConnection object
            responseCode = 0;
            System.out.println("Trying method 3 to get status code");

            // First we try parsing the exception message to see if it contains the response code
            Matcher exMsgStatusCodeMatcher = Pattern.compile("^Server returned HTTP response code: (\d+)").matcher(ex.getMessage());
            if(exMsgStatusCodeMatcher.find()) {
                responseCode = Integer.parseInt(exMsgStatusCodeMatcher.group(1));
            } else if(ex.getClass().getSimpleName().equals("FileNotFoundException")) {
                // 404 is a special case because it will throw a FileNotFoundException instead of having "404" in the message
                System.out.println("Got a FileNotFoundException");
                responseCode = 404;
            } else {
                // There can be other types of exceptions not handled here
                System.out.println("Exception (" + ex.getClass().getSimpleName() + ") doesn't contain status code: " + ex);
            }

            System.out.println("Status code from parsing exception message: " + responseCode);
            System.out.println();
        }

        System.out.println("-------");
        System.out.println();
    }

    public static void main(String []args) throws MalformedURLException {
        testUrl("https://httpbin.org/status/200");
        testUrl("https://httpbin.org/status/404");
        testUrl("https://httpbin.org/status/403");
        testUrl("http://nonexistingsite1111111.com");
    }
}

Output of the example code:

示例代码的输出:

Testing URL https://httpbin.org/status/200                                                                                                                                                                                        
Success!                                                                                                                                                                                                                          
-------                                                                                                                                                                                                                           

Testing URL https://httpbin.org/status/404                                                                                                                                                                                        
Error!                                                                                                                                                                                                                            

Trying method 2 to get status code                                                                                                                                                                                                
Status code from calling getResponseCode: 404                                                                                                                                                                                     

Trying method 3 to get status code                                                                                                                                                                                                
Got a FileNotFoundException                                                                                                                                                                                                       
Status code from parsing exception message: 404                                                                                                                                                                                   

-------

Testing URL https://httpbin.org/status/403                                                                                                                                                                                        
Error!                                                                                                                                                                                                                            

Trying method 2 to get status code                                                                                                                                                                                                
Status code from calling getResponseCode: 403                                                                                                                                                                                     

Trying method 3 to get status code                                                                                                                                                                                                
Status code from parsing exception message: 403                                                                                                                                                                                   

-------

Testing URL http://nonexistingsite1111111.com                                                                                                                                                                                     
Error!                                                                                                                                                                                                                            

Trying method 2 to get status code                                                                                                                                                                                                
getResponseCode threw: java.net.UnknownHostException: nonexistingsite1111111.com                                                                                                                                                  
Status code from calling getResponseCode: 0                                                                                                                                                                                       

Trying method 3 to get status code                                                                                                                                                                                                
Exception (UnknownHostException) doesn't contain status code: java.net.UnknownHostException: nonexistingsite1111111.com                                                                                                           
Status code from parsing exception message: 0                                                                                                                                                                                     

-------