繁体   English   中英

处理与服务器不存在的java.net.HttpURLConnection

[英]Handling java.net.HttpURLConnection to server that does not exist

尝试连接到不存在的主机/服务器时,我的程序似乎消失了。 单步调试器无济于事,它使它变为getResponseCode() ,然后停止工作。 我可以说的没有抛出异常,程序不会返回。

这是相关的代码片段:

    try {
        //construct a URL and open the connection
        URL url = new URL("http://" + serverHost + ":" + serverPort + urlSuffix);
        HttpURLConnection http = (HttpURLConnection)url.openConnection();

        http.setRequestMethod("POST");

        if(http.getResponseCode() != 200) {
            System.out.println("Could not connect");
        }
        System.out.println("Connected");

        return;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return;
    } catch (IOException e) {
        e.printStackTrace();
        return;
    } catch (Exception e) { //give me something please
        e.printStackTrace();
        return;
    }

连接到有效URL时,它可以正常工作。

我修复了它,我需要添加http.setConnectTimeout(10000); 打开连接后。 显然,无论将默认超时设置为多长时间,即使将应用程序保持打开状态几分钟,它也似乎根本无法给出响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM