2011-02-09 118 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如果不想再次抛出异常,按照你想要的方式处理它。