gpt4 book ai didi

android - HttpUrlConnection setConnectTimeout 不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:22:29 27 4
gpt4 key购买 nike

我正在尝试像这样使用 setConnectTimeout 函数:

protected HttpURLConnection getConnection() throws SocketTimeoutException, IOException{
Log.d("HTTPRequest", address);
URL page = new URL(address);
HttpURLConnection connection = (HttpURLConnection) page.openConnection();

connection.setUseCaches(cacheResult);
connection.setConnectTimeout(3000);
connection.connect();
return connection;
}

然后:

public String getTextData() throws InternetConnectionUnavailableException {
try{
HttpURLConnection conn = getConnection();
StringBuffer text = new StringBuffer();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;

while (true) {
if((line = buff.readLine()) != null){
text.append(line);
}else{
break;
}
}
return (text.toString());
} catch (SocketTimeoutException socketTimeoutException) {
throw new InternetConnectionUnavailableException();
} catch (IOException ioException) {
throw new InternetConnectionUnavailableException();
}
}

但是,它永远不会进入“catch (SocketTimeoutException socketTimeoutException)” block 。这里有什么问题。

附言为了进行测试,我制作了一个让我的服务器休眠 10 秒的页面。

最佳答案

试试这个:

try {

HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");

con.setConnectTimeout(5000); //set timeout to 5 seconds
con.setReadTimeout(socketTimeout);
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}

关于android - HttpUrlConnection setConnectTimeout 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11392601/

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