Android HttpsURLConnection is very slow to return 502 Bad Gateway

133 Views Asked by At

Update: They've changed the site. Instead of giving a generic 502 error from nginx it now gives an instant 403 with a custom message. This makes it impossible to reproduce the issue.

I have an app that gets data from Weather.gov. They're having an outage and I've discovered that HttpsURLConnection takes minutes to return the status.

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
  • If I open the link in my browser, it returns instantly.
  • If I do this as a desktop program, it also returns instantly.
  • As stated, it takes minutes to return in the Android Studio Emulator.
  • Adjusting the timeout makes no difference.

The question then is: How do I get the response back faster so that I can inform the user that there is a problem. It is, of course, in a thread so I can display a "Working" status, but I shouldn't need to. As stated, other systems come back with the status instantly.

Note: Someone is probably dying to tell me to use a different weather source. That would be missing the point. Connection issues happen all the time, I want the app to be better about them.

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) 
1

There are 1 best solutions below

4
On

Well after seeing CommonsWare using OkHttp with nice result i would contribute that that url gives an IOException within a second (on a real device) using HttpUrlConnection.

But i open an input stream and try to read. Not looking at a resultcode at all...

Why would one look at a resultcode if one would grab the page content..