2016-05-18 4 views
-1

Как возможно (если вообще) получить код статуса HTTP из java.io.IOException in java ?Извлечь код состояния HTTP из java.io.IOException

+1

Какой статус вы говорите? Вы говорите о каком-то подклассе 'IOException', который содержит код состояния? –

+0

язык? пример? – xAqweRx

+0

Язык написан в тегах: Java – CherryDT

ответ

4

Я предполагаю, что это примерно IOException, выброшенное URLConnection.

Три возможности справиться с этим, в зависимости от ваших ограничений.

1) В ролях ваши URLConnection к HttpURLConnection и вызвать getResponseCode

Если у вас есть доступ к объекту соединения, вы можете получить код состояния, используя этот код:

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

2) Используйте HttpURLConnection вместо URLConnection в первую очередь

Если вы c сделайте это, это будет лучшее решение, потому что URLConnection не набрасывает коды состояния ошибок. Вы можете просто позвонить getResponseCode и проверить статус без каких-либо исключений.

3) Разобрать сообщение об исключении самого

СООБЩЕНИЯ IOException «s обычно выглядит следующим образом:

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 1 to get status code                                                 
Status code from calling getResponseCode: 404                                              

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

------- 

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

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

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

------- 

Testing URL http://nonexistingsite1111111.com                                              
Error!                                                        

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

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

-------                                                       
+0

Можете ли вы объяснить, как «Вы можете просто вызвать getResponseCode и проверить статус без предварительного исключения». применяется к варианту 2, но не к варианту 1? Если вы можете включить URLConnection в HttpURLConnection, то это * было * HttpURLConnection "в первую очередь", и тот факт, что он был доставлен вам как URLConnection, не меняет это? – Rodney

+0

Это применимо к обоим - снова прочитайте мой вариант 1;) Я просто хотел, чтобы вы могли создать его как HttpURLConnection или перенести его позже. В обоих случаях вы можете вызвать getResponseCode. – CherryDT