java.net.URL 如何打开连接?它使用套接字吗?
我使用以下代码从 URL 获取 JSON 字符串:
public static String getStringFromURL(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
org.apache.commons.io.IOUtils.copy(url.openStream(), output);
return output.toString();
}
我想确保如果“addr”处的页面因任何原因失败,这不会挂起。我不希望它使我们的服务器瘫痪或发生任何事情。我们开始研究 java.net.URL 如何打开连接,但无法从 Javadoc(我们使用的是 1.5)。任何想法或内部知识将不胜感激。如果你能引用来源,那就更好了。谢谢!
I'm using the following code to get a JSON string from a URL:
public static String getStringFromURL(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
org.apache.commons.io.IOUtils.copy(url.openStream(), output);
return output.toString();
}
I want to make sure this doesn't hang if the page at "addr" fails for any reason. I don't want it to bring our server down or anything. We started looking into how java.net.URL opens the connection and couldn't tell much from the Javadoc (we are using 1.5). Any thoughts or inside knowledge would be appreciated. If you can cite sources, so much the better. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从技术上讲,这取决于协议。对于 HTTP,它使用 TCP/IP 套接字。如果发生 I/O 错误,
openStream()
将引发异常。只需将其放入 try/catch 中即可。但是,如果服务器返回例如 HTTP 404(未找到)或 500(内部错误),您将在不知不觉中将此明文放入字符串中。您可能需要使用HttpURLConnection
来进行更细粒度的控制。此外,您可以设置超时 <代码>URLConnection#setConnectTimeout()。我相信,它默认为 3 秒左右。您可能需要对其进行调整以使其更快。设置
1000
1 秒。Technically, that depends on the protocol. For HTTP, it uses TCP/IP sockets. The
openStream()
will throw an exception if an I/O error occurs. Just put it in a try/catch. However, if the server returns for example a HTTP 404 (not found) or 500 (internal error), you will get this plain into the string unawarely. You may want to useHttpURLConnection
instead for more fine-grained control.Further you can set the timeout
URLConnection#setConnectTimeout()
. I believe, it defaults to 3 seconds or something. You may want to tweak it to make it all faster. Set with1000
for 1 second.是的,它会挂起。
有两个超时需要考虑:
Yes, it will hang.
There are two timeouts to consider: