2011-02-09 130 views
0

我正在嘗試與服務器進行通信的503響應。現在,它在日誌中向我顯示了這一點,但是,我希望捕獲它觸發並處理它的IOException,當且僅當響應代碼是503時,並且沒有其他事件。我將如何做到這一點?Java HTTP響應代碼,URL,IOException

編輯:

這裏是我的代碼部分:

inURL = new BufferedReader(new InputStreamReader(myURL.openStream())); 

String str; 
while ((str = inURL.readLine()) != null) { 
    writeTo.write(str + "\n"); 
} 

inURL.close(); 
+0

您使用的是什麼HTTP客戶端API? – BalusC 2011-02-09 15:10:32

回答

4

如果使用java.net.HttpURLConnection,使用方法getResponseCode()

如果使用org.apache.commons.httpclient.HttpClientexecuteMethod(...)返回響應代碼

0

這裏是一個了HTTPClient我做:

public class HTTPClient { 

    /** 
    * Request the HTTP page. 
    * @param uri the URI to request. 
    * @return the HTTP page in a String. 
    */ 
    public String request(String uri){ 

     // Create a new HTTPClient. 
     HttpClient client = new HttpClient(); 
     // Set the parameters 
     client.getParams().setParameter("http.useragent", "Test Client"); 
     //5000ms 
     client.getParams().setParameter("http.connection.timeout",new Integer(5000)); 

     GetMethod method = new GetMethod(); 

     try{ 
      method.setURI(new URI(uri, true)); 
      int returnCode = client.executeMethod(method); 

      // The Get method failed. 
      if(returnCode != HttpStatus.SC_OK){ 
       System.err.println("Unable to fetch default page," + 
         " status code : " + returnCode); 
      } 

      InputStream in = method.getResponseBodyAsStream(); 

      // The input isn't null. 
      if (in != null) { 
       StringBuilder sb = new StringBuilder(); 
       String line; 

       try { 
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); 
        while ((line = reader.readLine()) != null) { 
         sb.append(line).append("\n"); 
        } 
       } finally { 
        in.close(); 
       } 
       //return statement n0 
       return sb.toString(); 
        } 
      else { 
       //return statement n1 
       return null; 
      } 

     } catch (HttpException he) { 
      System.err.println(" HTTP failure"); 
     } catch (IOException ie) { 
      System.err.println(" I/O problem"); 
     } finally { 
      method.releaseConnection(); 
     } 
     //return statement n2 
     return null;   
    } 
} 

也許它可以幫助你。

0

句柄,如果它落入該代碼段你想要IOException異常的catch子句的情況。

檢查http狀態碼是否爲503如果不想再次拋出異常,按照你想要的方式處理它。

相關問題