gpt4 book ai didi

android - 等待但未抛出 SocketTimeoutException?

转载 作者:行者123 更新时间:2023-11-30 04:21:50 26 4
gpt4 key购买 nike

我正在编写一个从服务器接收数据的 Android 应用程序。理论上不可能有互联网连接,所以我尝试通过捕获 SocketTimeoutException 来显示错误消息重试屏幕或其他内容来捕获这种情况。不幸的是,不会抛出此异常。至少它不会跳入 catch 子句。我做错了什么?

public class HttpConnector {

private String urlString;
private int connectionTimeout = 5000; //milliseconds

public HttpConnector(String urlString) {
this.urlString = urlString;
}

public String receiveData() throws PolizeiwarnungException {
URL url = null;
HttpURLConnection urlConnection = null;
StringBuffer b = new StringBuffer();

try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(connectionTimeout);
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); //Here it gets stuck if there is no connection to the server

String str;
while ((str = reader.readLine()) != null) {
b.append(str + "\n");
}
}
catch (SocketTimeoutException e) {
//TODO
e.printStackTrace();
}
catch (IOException e) {
throw new PolizeiwarnungException(e);
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}

return b.toString();
}

public void sendData(String data) {
//TODO
}
}

最佳答案

您还需要设置连接超时。 Please see this documentation.

由于终点不存在,如果没有设置连接超时,连接将永远不会超时。

setConnectTimeout(int timeout) Sets the timeout value in milliseconds for establishing the connection to the resource pointed by this URLConnection instance.

关于android - 等待但未抛出 SocketTimeoutException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9140143/

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