【问题标题】:Extract HTTP Status Code from java.io.IOException从 java.io.IOException 中提取 HTTP 状态码
【发布时间】:2016-09-15 02:49:04
【问题描述】:

如何(如果有的话)从java.io.IOException in java 获取 HTTP 状态代码?

【问题讨论】:

  • 你在说什么状态码?你是在谈论一些包含状态码的IOException 子类吗?
  • 语言?例如?
  • 语言写在标签里:Java
  • 请举个例子。
  • 我在java.io.Exception 中没有看到任何状态码。

标签: java http ioexception http-status-codes


【解决方案1】:

我假设这是关于由 URLConnection 抛出的 IOException

三种可能的处理方式,取决于您的限制。

1) 将您的 URLConnection 转换为 HttpURLConnection 并调用 getResponseCode

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

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

2) 首先使用HttpURLConnection 而不是URLConnection

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

3) 解析异常消息本身

IOException 的消息通常如下所示:

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

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

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

演示方法 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");
    }
}

示例代码的输出:

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                                                                                                                                                                                     

-------                                                                                                                                                                                                                           

【讨论】:

  • 您能否解释一下“您可以只调用 getResponseCode 并检查状态而不首先获得任何异常。”适用于选项 2 但不适用于选项 1?如果您可以将 URLConnection 转换为 HttpURLConnection,那么它“首先”是一个 HttpURLConnection,并且它作为 URLConnection 传递给您的事实不会改变这一点?
  • 它适用于两者 - 再次阅读我的选项 1 ;) 我的意思是您可以首先将其创建为 HttpURLConnection 或稍后将其转换为一个。在这两种情况下,您都可以调用 getResponseCode。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-05
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
相关资源
最近更新 更多