gpt4 book ai didi

Java URL 类 openStream 抛出 java.net.ConnectException : Connection refused: connect

转载 作者:行者123 更新时间:2023-12-03 02:02:27 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的程序来显示各种 URL 的内容。我的代码是这样的。

    import java.io.IOException;
import java.io.InputStream;
import java.net.*;

public class test {
public static void main(String[] args) {
URL url;
//String site ="ftp://ftp.suse.com/";
//String site ="http://www.google.ca";
//String site = "ftp://ftp.gnu.org/README";
String site = "ftp://metalab.unc.edu/";
try {
url = new URL(site);
InputStream stream = url.openStream();
for(int i = 0;i!= -1;i= stream.read()){
System.out.print((char)i);
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

前 3 个资源很好

  • 字符串站点 ="ftp://ftp.suse.com/";
  • 字符串站点 =“http://www.google.ca”;
  • String site = "ftp://ftp.gnu.org/README";

但是最后一个

  • 字符串站点 =“ftp://metalab.unc.edu/”;

产生以下错误

    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.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.ftp.impl.FtpClient.openPassiveDataConnection(Unknown Source)
at sun.net.ftp.impl.FtpClient.openDataConnection(Unknown Source)
at sun.net.ftp.impl.FtpClient.list(Unknown Source)
at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.main(test.java:13)

我尝试过的其他各种 ftp 站点也会发生这种情况。 HTTP 站点没有遇到任何问题。有什么想法可以解决这个问题。我可以从浏览器访问的所有指定资源。

最佳答案

该网站可能是refusing non-browser user agents 。您可以尝试设置用户代理:

URL url;
String site = "ftp://metalab.unc.edu/";
try {
url = new URL(site);
URLConnection urlc = url.openConnection();
urlc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0a2) Gecko/20110613 Firefox/6.0a2");
InputStream stream = urlc.getInputStream();
for(int i = 0;i!= -1;i= stream.read()){
System.out.print((char)i);
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}

关于Java URL 类 openStream 抛出 java.net.ConnectException : Connection refused: connect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7731673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com