I'm getting a 503 response from a server that I'm trying to communicate with. Now, it shows me this in the log, but, I want to catch the IOException that it fires and deal with it if and only if the response code is 503, and nothing else. How would I do this?
EDIT:
Here's part of my code:
inURL = new BufferedReader(new InputStreamReader(myURL.openStream()));
String str;
while ((str = inURL.readLine()) != null) {
writeTo.write(str + "\n");
}
inURL.close();
If using java.net.HttpURLConnection
, use the method getResponseCode()
If using org.apache.commons.httpclient.HttpClient
, executeMethod(...)
returns the response code
Handle the case you want in you IOEXception catch clause if it falls into that code section.
Check the http status code if it is 503 handle it the way you want, if not throw the exception again.
here's an HTTPClient I have done :
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;
}
}
Maybe it can help you.