java url buffer,如何根据Java中的URLConnection对BufferedReader设置超时?

博客内容讨论了在不使应用程序挂起的情况下,如何从URL读取内容并设置超时。通过使用URLConnection的setReadTimeout方法,可以避免因URL响应慢而导致的读取操作挂起,从而确保程序的正常运行。
摘要由CSDN通过智能技术生成

I want to read the contents of a URL but don't want to "hang" if the URL is unresponsive. I've created a BufferedReader using the URL...

URL theURL = new URL(url);

URLConnection urlConn = theURL.openConnection();

urlConn.setDoOutput(true);

BufferedReader urlReader = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));

...and then begun the loop to read the contents...

do

{

buf = urlReader.readLine();

if (buf != null)

{

resultBuffer.append(buf);

resultBuffer.append("\n");

}

}

while (buf != null);

...but if the read hangs then the application hangs.

Is there a way, without grinding the code down to the socket level, to "time out" the read if necessary?

解决方案

I think URLConnection.setReadTimeout is what you are looking for.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值