Home » Android » Android java.net.UnknownHostException: Host is unresolved (strategy question)

Android java.net.UnknownHostException: Host is unresolved (strategy question)

Posted by: admin June 15, 2020 Leave a comment


I have android code that uses a background process to routinely (e.g. hourly) connect to a content source on the web to check for updated content. As new users download the app and run it for the first time, it seems (and this is just a “seems at the moment) that in this first-run situation, because the DNS for our servers are not cached already on the device, those first series of connections fail with dreaded UnknownHostException: Host is unresolved. And of course, the application tries again later and (again, “it seems like”) it is all working — perhaps because the OS has had time to actually resolve the address.

So, my question(s) are: (1) Do other Android developers see this behavior with their deployed applications as well? First time, a series of “host unresolved” issues that work themselves out later. (2) Does anyone have a better strategy for “warming up the DNS” so-to-speak so that the first real connections work? or perhaps do you just re-try with some back-off looping when you encounter this exception? I was contemplating having a separate thread that tries to fetch a small text file from our server and have it just loop until it gets it and maybe (not sure about this part) block the other outgoing network connections until it succeeds.

In any event, I have read through a chunk of the answers to various similarly worded questions here on Stack Overflow and I just to assure everyone that

<uses-permission android:name="android.permission.INTERNET" />

is set in my Manifest file 🙂

How to&Answers:

I have come across this behaviour while using HttpUrlConnection. I am using simple workaround – I execute the following code just before using any url.

    try {
      InetAddress i = InetAddress.getByName(URLName);
    } catch (UnknownHostException e1) {
// ... actually using URLName

For the first time I obtain here UnknownHostException but next usages of the url are successful (DNS server returns proper IP address and I can connect to the server).