为啥 ConnectException:连接被拒绝:从 HttpURLConnection.getResponseCode() 抛出连接? [复制]

Posted

技术标签:

【中文标题】为啥 ConnectException:连接被拒绝:从 HttpURLConnection.getResponseCode() 抛出连接? [复制]【英文标题】:why ConnectException: Connection refused: connect is thrown from HttpURLConnection.getResponseCode()? [duplicate]为什么 ConnectException:连接被拒绝:从 HttpURLConnection.getResponseCode() 抛出连接? [复制] 【发布时间】:2019-11-30 03:33:44 【问题描述】:

为什么HttpURLConnection.getResponseCode() 会抛出ConnectException: Connection refused: connect 异常?

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.getResponseCode(); // this line

例外是:

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.datasoft.cbsdit.CbsditApplication.main(CbsditApplication.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

【问题讨论】:

您确定您尝试连接的远程服务器是可访问的吗? 因为该 IP:port 上没有任何东西在监听。你为什么打电话给getResponseCode()却忽略了结果? 【参考方案1】:

远程机器 URL 不正确或远程服务器已关闭, 如果您尝试使用有效的 url 值(例如:https://***.com),则上述代码可以正常工作:)

【讨论】:

以上是关于为啥 ConnectException:连接被拒绝:从 HttpURLConnection.getResponseCode() 抛出连接? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

docker和nginx部署:java.net.ConnectException:连接被拒绝(连接被拒绝)

Heroku/Postgres:引起:java.net.ConnectException:连接被拒绝(连接被拒绝)

Bug修改日记:连接被拒绝: ConnectException

java.net.ConnectException:连接被拒绝

Tomcat:java.net.ConnectException:连接被拒绝

java.net.ConnectException:连接被拒绝:连接 HTTPS 连接