gpt4 book ai didi

java.net.SocketException : Network is unreachable: connect 异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:36 25 4
gpt4 key购买 nike

我正在尝试使用此方法从 Web 服务器下载 xml 文本文件:

static void download (String url , String fileName) throws IOException{

FileWriter xmlWriter;
xmlWriter = new FileWriter(fileName);
System.out.println("URL to download is : " + url);

// here Exception is thrown/////////////////////////////////
BufferedReader inputTxtReader = new BufferedReader
(new BufferedReader(new InputStreamReader(addURL.openStream())));
////////////////////////////////////////////////////////

String str ;
String fileInStr = "";

str = inputTxtReader.readLine();

while (!(str == null) ){///&& !(str.equals("</tv>"))
fileInStr += (str + "\r\n");
str = inputTxtReader.readLine();
}

xmlWriter.write(fileInStr);
xmlWriter.flush();
xmlWriter.close();
System.out.println("File Downloaded");
}

有时会抛出这个异常(我指定的地方是代码):

java.net.SocketException: Network is unreachable: connect
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:518)
at java.net.Socket.connect(Socket.java:468)
at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:389)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:516)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:318)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:788)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:729)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:654)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:977)
at java.net.URL.openStream(URL.java:1009)
at MessagePanel.download(MessagePanel.java:640)
at WelcomThread.run(MainBody2.java:891)

请指导我

谢谢大家

最佳答案

您正面临连接中断。这会发生在 3G、WiFi 或计算机上的“普通”连接中吗?

无论如何,在编写您的应用程序时,您必须假设连接可能会不时丢失。例如,对于手机,这种情况经常发生在管道、地下室等地方。对于 PC 应用程序,这种情况不太常见,但有时会发生。

重试可能是一个很好的解决方案。并且解释网络的清晰错误消息此时也不可用。

关于java.net.SocketException : Network is unreachable: connect 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6826331/

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