Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
Want to improve this question?
Add details and clarify the problem by
editing this post
.
Closed
5 years ago
.
How to handle this error: java.io.IOException: Server returned HTTP response code: 503 for
I wish that when gave this error, my code would repeat the request of url.
No is none this errors:
1) The server may be busy
2) The server may be down for maintenance
Code:
public Element trataDados(String address1) throws MalformedURLException, IOException, JDOMException {
URL url;
url = new URL(address1);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader bfreader = new BufferedReader(reader);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bfreader.readLine()) != null) {
stringBuilder.append(line);
bfreader.close();
conn.disconnect();
Get the response code before you start reading the input. If it's 503, don't read the input, do read the error stream, and close it, and then retry, but not too soon. If the server is down for maintenance it could be for five seconds or five days. You should probably use an exponentially-increasing retry interval like TCP does, say doubling it every time, or multiplying by 1.5, up to some limit where you just give up.
NB GET is already the default.
public Element trataDados(String address1) throws MalformedURLException, IOException, JDOMException {
URL url;
HttpURLConnection conn;
url = new URL(address1);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//test out
System.out.println("REQUEST: "+conn.getResponseCode());
System.out.println("REQUEST: "+conn.getResponseMessage());
}while(conn.getResponseCode()!= HttpURLConnection.HTTP_OK);
InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader bfreader = new BufferedReader(reader);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bfreader.readLine()) != null) {
stringBuilder.append(line);
bfreader.close();
conn.disconnect();
–
–