我有一个从 Weather.gov 获取数据的应用程序。他们发生了中断,我发现 HttpsURLConnection 需要几分钟才能返回状态。
String urlString = "https://api.weather.gov/gridpoints/VEF/127,91/forecast";
HttpsURLConnection connection = (HttpsURLConnection) new URL (urlString).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
connection.setReadTimeout (1000);
int responseCode = connection.getResponseCode (); // This doesn't return for a minute or three
接下来的问题是:如何更快地得到响应,以便我可以通知用户存在问题。当然,它在一个线程中,因此我可以显示“正在工作”状态,但我不需要这样做。如前所述,其他系统会立即返回状态。
注意:有人可能很想告诉我使用不同的天气源。那样的话就没有抓住要点。连接问题总是发生,我希望应用程序能够更好地解决这些问题。
Android Studio Giraffe | 2022.3.1 Patch 1
Build #AI-223.8836.35.2231.10671973, built on August 17, 2023
Runtime version: 17.0.6+0-b2043.56-10027231 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
My desktop JDK is:
openjdk version "19.0.2" 2023-01-17
OpenJDK Runtime Environment (build 19.0.2+7-44)
在看到 CommonsWare 使用 OkHttp 取得不错的结果后,我会贡献一下,该 url 使用 HttpUrlConnection 会在一秒钟内(在真实设备上)给出 IOException。
但是我打开一个输入流并尝试读取。根本不看结果代码...
如果要抓取页面内容,为什么要查看结果代码..