为什么当URL启动时会出现“java.net.ConnectException:Connection超时”异常?

我从我的代码中得到一些频率。我试图点击的网址已启动。相同的代码适用于某些用户,但不适用于其他用户。似乎一旦一个用户开始获得此异常,他们就会继续获得异常。ConnectException: Connection timed out

下面是堆栈跟踪:

java.net.ConnectException: Connection timed out
Caused by: java.net.ConnectException: Connection timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.Socket.connect(Socket.java:516)
    at java.net.Socket.connect(Socket.java:466)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:365)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:477)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
    at sun.net.www.http.HttpClient.New(HttpClient.java:287)
    at sun.net.www.http.HttpClient.New(HttpClient.java:299)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:796)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:748)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:673)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:840)

下面是我的代码中的一个片段:

URLConnection urlConnection = null;
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;

try {
    URL url = new URL(urlBase);
    urlConnection = url.openConnection();
    urlConnection.setDoOutput(true);

    outputStream = urlConnection.getOutputStream(); // exception occurs on this line
    outputStreamWriter = new OutputStreamWriter(outputStream);
    outputStreamWriter.write(urlString);
    outputStreamWriter.flush();
    inputStream = urlConnection.getInputStream();
    String response = IOUtils.toString(inputStream);
    return processResponse(urlString, urlBase, response);
} catch (IOException e) {
    throw new Exception("Error querying url: " + urlString, e);
} finally {
    IoUtil.close(inputStream);
    IoUtil.close(outputStreamWriter);
    IoUtil.close(outputStream);
}

答案 1

连接超时(假设有本地网络和多台客户端计算机)通常由

a)途中的某种防火墙,它只是吃掉数据包,而不会告诉发件人诸如“没有到主机的路由”之类的事情

b) 由于网络配置错误或线路过载导致丢包

c) 请求过多,导致服务器过载

d)服务器上少量同时可用的线程/进程,导致所有这些线程/进程都被占用。对于需要很长时间才能运行并且可能与c组合的请求,尤其会发生这种情况。

希望这有帮助。


答案 2

如果 URL 在同一台计算机上的 Web 浏览器中工作正常,则可能是 Java 代码未使用浏览器用于连接到 URL 的 HTTP 代理。


推荐