我正在使用以下代码从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)中得到很多信息。任何想法或内部知识将不胜感激。如果你能引用消息来源,那就更好了。谢谢!
答案 0 :(得分:6)
从技术上讲,这取决于协议。对于HTTP,它使用TCP / IP套接字。如果发生I / O错误,openStream()
将抛出异常。把它放在try / catch中。但是,如果服务器返回例如HTTP 404(未找到)或500(内部错误),您将无意识地将其明确地转换为字符串。您可能希望使用HttpURLConnection
来进行更精细的控制。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseStatus() == 200) {
// All OK, convert connection.getInputStream() to string.
// Don't forget to take character encoding into account!
} else {
// Possible server error. Throw exception yourself? Or return some default?
}
此外,您可以设置超时URLConnection#setConnectTimeout()
。我相信,默认为3秒或者其他什么。您可能想要调整它以使其更快。使用1000
设置1秒钟。
答案 1 :(得分:5)
是的,它会挂起。
有两种超时需要考虑: