我从我正在尝试与之通信的服务器获得503响应。现在,它在日志中向我显示了这一点,但是,我想要捕获它触发并处理它的IOException,当且仅当响应代码是503时,没有别的。我该怎么做?
编辑:
这是我的代码的一部分:
inURL = new BufferedReader(new InputStreamReader(myURL.openStream()));
String str;
while ((str = inURL.readLine()) != null) {
writeTo.write(str + "\n");
}
inURL.close();
答案 0 :(得分:4)
如果使用java.net.HttpURLConnection
,请使用方法getResponseCode()
如果使用org.apache.commons.httpclient.HttpClient
,则executeMethod(...)
会返回响应代码
答案 1 :(得分: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;
}
}
也许它可以帮到你。
答案 2 :(得分:0)
如果IOEXception catch子句属于该代码部分,则处理你想要的案例。
检查http状态代码,如果它是503,你可以按照你想要的方式处理它,如果没有再次抛出异常。