2016-05-18 5 views
-1

Wie ist es möglich (wenn überhaupt), den HTTP-Statuscode von einer java.io.IOException in java zu erhalten?HTTP-Statuscode aus java.io.IOException extrahieren

+1

Welche Statuscode sprichst du? Sprechen Sie über eine Unterklasse namens 'IOException', die einen Statuscode enthält? –

+0

Sprache? Beispiel? – xAqweRx

+0

Sprache ist in den Tags geschrieben: Java – CherryDT

Antwort

4

Ich gehe davon aus, dass dies über eine IOException von einer URLConnection geworfen wird.

Drei Möglichkeiten, dies zu handhaben, abhängig von Ihren Einschränkungen.

1) Werfen Sie Ihre URLConnection zu einem HttpURLConnection und getResponseCode

rufen Wenn Sie Zugriff auf das Connection-Objekt haben, können Sie den Statuscode mit diesem Code erhalten:

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

2) Verwenden Sie eine HttpURLConnection anstelle einer URLConnection an erster Stelle

Wenn Sie c Dies wäre die beste Lösung, denn ein URLConnection wirft keine Fehlerstatuscodes auf. Sie können einfach getResponseCode anrufen und den Status überprüfen, ohne zuerst eine Ausnahme zu erhalten.

3) Analysieren Sie die Ausnahmemeldung selbst

Die IOException ‚s Nachricht in der Regel wie folgt aussieht:

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

So können Sie nur verwenden, um einen regulären Ausdruck (oder einfache String-Manipulation) die bekommen Antwortcode von dort.

Beachten Sie, dass die Nachricht für Status 404 nicht so aussieht und FileNotFoundException ausgelöst wird. Ich bin nicht sicher, ob es irgendwelche anderen Statuscodes gibt, die "spezielle" Ausnahmen wie diese werfen, aber pass auf das auf.

Beispielcode demonstriert Methoden 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"); 
    } 
} 

Ausgabe des Beispielcode:

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

Können Sie erklären, wie "Sie getResponseCode aufrufen und den Status überprüfen können, ohne zuerst eine Ausnahme zu erhalten." gilt für Option 2, aber nicht für Option 1? Wenn Sie die URLConnection in eine HttpURLConnection umwandeln können, dann war es * eine HttpURLConnection "an erster Stelle" und die Tatsache, dass es Ihnen als URLConnection geliefert wurde, ändert das nicht? – Rodney

+0

Es gilt für beide - lesen Sie meine Option 1 erneut;) Ich meinte nur, dass Sie es entweder als HttpURLConnection in erster Linie erstellen oder es zu einem späteren Zeitpunkt umwandeln können. In beiden Fällen können Sie getResponseCode aufrufen. – CherryDT