【问题标题】:Handling java.net.HttpURLConnection to server that does not exist处理 java.net.HttpURLConnection 到不存在的服务器
【发布时间】:2017-03-26 19:15:05
【问题描述】:

在尝试连接到不存在的主机/服务器时,我的程序似乎死了。使用调试器单步执行对我没有任何帮助,它会到达getResponseCode(),然后停止工作。根据我的判断,没有抛出异常,程序也没有返回。

这里是相关代码sn-p:

    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 时,它可以正常工作。

【问题讨论】:

  • 确保在任何情况下都读取输入流(尤其是错误)

标签: java http httpurlconnection


【解决方案1】:

我修好了,我需要在打开连接后添加http.setConnectTimeout(10000);。显然,无论默认超时设置为何如此之长,以至于它似乎根本不会给出响应,即使让应用程序打开几分钟也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多