在Java中超时重试连接 [英] Retry a connection on timeout in Java

查看:97
本文介绍了在Java中超时重试连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法(如下),该方法可以下拉并以String形式返回网页的来源.一切正常且繁琐,但是当连接超时时,程序将引发异常并退出.有没有更好的方法可以执行此操作以允许它在超时时重试,还是有办法在此方法内进行操作?

I have a method (below) that pulls down and returns the source of a webpage as a String. It all works fine and dandy, but when the connection times out, the program throws an exception and exits. Is there a better method to do this that would allow it to try again on timeout, or is there a way to do it within this method?

public static String getPage(String theURL) {
    URL url = null;
    try {
        url = new URL(theURL);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        exitprint();
    }
    InputStream is = null;
    try {
        is = url.openStream();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        exitprint();
    }
    int ptr = 0;
    StringBuffer buffer = new StringBuffer();
    try {
        while ((ptr = is.read()) != -1) {
            buffer.append((char)ptr);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        exitprint();
    }

    return buffer.toString();
}

推荐答案

这是代码的重构,应重试下载 N 次.虽然尚未进行测试,但是它应该将您引向正确的方向.

Here's a refactoring of your code that should retry the download N times. Haven't tested it though, but it should kick you off in the right direction.

public static String getPage(String theURL) {

    URL url = null;
    try {
        url = new URL(theURL);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        exitprint();
    }

    for (int i = 0; i < N; i++) {

        try {
            InputStream is = url.openStream();

            int ptr = 0;
            StringBuffer buffer = new StringBuffer();

            while ((ptr = is.read()) != -1)
                buffer.append((char)ptr);

        } catch (IOException e) {
            continue;
        }

        return buffer.toString();
    }

    throw new SomeException("Failed to download after " + N + " attepmts");
}

这篇关于在Java中超时重试连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆