How to handle this error: java.io.IOException: Server returned HTTP response code: 503 for

How to handle this error: java.io.IOException: Server returned HTTP response code: 503 for

如何处理此错误:java.io.IOException:服务器返回 HTTP 响应代码:503 for

我希望在出现此错误时,我的代码会重复 url 的请求。

不是none这个错误:

1) 服务器可能正忙

2) 服务器可能停机维护

代码:

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();

在开始读取输入之前获取响应代码。如果是 503,不要读取输入,读取错误流,关闭它,然后重试,但不要太早。如果服务器因维护而停机,则可能需要五秒钟或五天。您可能应该像 TCP 一样使用指数增加的重试间隔,比如每次加倍,或者乘以 1.5,直到达到某个您放弃的极限。

注意 GET 已经是默认值。

Thanks @EJP, 
based on your answer I solved my question thus:



    public Element trataDados(String address1) throws MalformedURLException, IOException, JDOMException {

        URL url;
        HttpURLConnection conn;

    do{
        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();