Android HttpsURLConnection 非常慢返回 502 Bad Gateway

问题描述 投票:0回答:1

我有一个从 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 模拟器。
  • 调整超时没有什么区别。

接下来的问题是:如何更快地得到响应,以便我可以通知用户存在问题。当然,它在一个线程中,因此我可以显示“正在工作”状态,但我不需要这样做。如前所述,其他系统会立即返回状态。

注意:有人可能很想告诉我使用不同的天气源。那样的话就没有抓住要点。连接问题总是发生,我希望应用程序能够更好地解决这些问题。

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) 
java android android-studio httpsurlconnection
1个回答
0
投票

在看到 CommonsWare 使用 OkHttp 取得不错的结果后,我会贡献一下,该 url 使用 HttpUrlConnection 会在一秒钟内(在真实设备上)给出 IOException。

但是我打开一个输入流并尝试读取。根本不看结果代码...

如果要抓取页面内容,为什么要查看结果代码..

© www.soinside.com 2019 - 2024. All rights reserved.