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

时间:2018-04-17 20:55:13

标签: java http-status-code-503

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

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

否是这个错误:

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

2 个答案:

答案 0 :(得分:0)

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

NB GET已经是默认值。

答案 1 :(得分:-1)

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