[java] java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I've created an app that loads a question from my web services, and it works fine. But, sometimes it crashes and I do not get the reason why this is happening, especially because I have also given it the required permissions. It works fine, but at random, it crashes and gives me this report.

private void sendContinentQuestions(int id) {
    // TODO Auto-generated method stub

    //Get the data (see above)
    JSONArray json = getJSONfromURL(id);
        try{
            for(int i=0; i < json.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject jObject = json.getJSONObject(i);
                longitude":"72.5660200"
                String category_id = jObject.getString("category_id");
                String question_id = jObject.getString("question_id");
                String question_name = jObject.getString("question_name");
                String latitude = jObject.getString("latitude");
                String longitude = jObject.getString("longitude");
                String answer = jObject.getString("answer");
                String ansLatLng = latitude+"|"+longitude ; 
                Log.v("## data:: ###",question_id+"--"+question_name+"-cat id-"+category_id+"--ansLatLng "+ansLatLng+" answer: "+answer);

                all_question.add(new QuestionData(game_id,category_id,question_id,question_name,ansLatLng,answer));
            }
        }catch(JSONException e)        {
            Log.e("log_tag", "Error parsing data "+e.toString());
        }
    }


}
 public JSONArray getJSONfromURL(int id){

    String response = "";
    URL url;
    try {
        url = new URL(Consts.GET_URL+"index.php/Api/getQuestion?cat_id="+id);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setRequestMethod("POST");
        InputStream is = http.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        response = br.readLine();
        Log.v("###Response :: ###",response);
        http.disconnect();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(); 
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    //try parse the string to a JSON object
    JSONArray jArray = null;
    try{

        jArray = new JSONArray(response);

    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
}

11-13 15:02:52.307: W/System.err(8012): java.net.UnknownHostException: Unable to resolve host "www.xyz.com": No address associated with hostname
11-13 15:02:52.317: W/System.err(8012):     at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
11-13 15:02:52.317: W/System.err(8012):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-13 15:02:52.317: W/System.err(8012):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
11-13 15:02:52.317: W/System.err(8012):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
11-13 15:02:52.327: W/System.err(8012):     at com.abc.xyz.ContinentActivity.getJSONfromURL(ContinentActivity.java:400)
11-13 15:02:52.327: W/System.err(8012):     at com.abc.xyz.ContinentActivity.sendContinentQuestions(ContinentActivity.java:327)
11-13 15:02:52.327: W/System.err(8012):     at com.abc.xyz.ContinentActivity.access$2(ContinentActivity.java:323)
11-13 15:02:52.327: W/System.err(8012):     at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:254)
11-13 15:02:52.327: W/System.err(8012):     at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:1)
11-13 15:02:52.327: W/System.err(8012):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-13 15:02:52.327: W/System.err(8012):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-13 15:02:52.327: W/System.err(8012):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-13 15:02:52.327: W/System.err(8012):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-13 15:02:52.337: W/System.err(8012):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-13 15:02:52.337: W/System.err(8012):     at java.lang.Thread.run(Thread.java:841)
11-13 15:02:52.337: W/System.err(8012): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
11-13 15:02:52.337: W/System.err(8012):     at libcore.io.Posix.getaddrinfo(Native Method)
11-13 15:02:52.337: W/System.err(8012):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
11-13 15:02:52.337: W/System.err(8012):     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
11-13 15:02:52.337: W/System.err(8012):     ... 24 more
11-13 15:02:52.337: E/log_tag(8012): Error parsing data org.json.JSONException: End of input at character 0 of 
11-13 15:02:52.337: W/dalvikvm(8012): threadid=194: thread exiting with uncaught exception (group=0x417c1700)
11-13 15:02:52.337: E/AndroidRuntime(8012): FATAL EXCEPTION: AsyncTask #5
11-13 15:02:52.337: E/AndroidRuntime(8012): java.lang.RuntimeException: An error occured while executing doInBackground()
11-13 15:02:52.337: E/AndroidRuntime(8012):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at java.lang.Thread.run(Thread.java:841)
11-13 15:02:52.337: E/AndroidRuntime(8012): Caused by: java.lang.NullPointerException
11-13 15:02:52.337: E/AndroidRuntime(8012):     at com.abc.xyz.ContinentActivity.sendContinentQuestions(ContinentActivity.java:328)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at com.abc.xyz.ContinentActivity.access$2(ContinentActivity.java:323)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:254)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at com.abc.xyz.ContinentActivity$LoadQuestions.doInBackground(ContinentActivity.java:1)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-13 15:02:52.337: E/AndroidRuntime(8012):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)

This question is related to java android web-services android-asynctask

The answer is


I had the same problem. java.net.UnknownHostException: Unable to resolve host “”...

I'm running Visual Studio 2019 and Xamarin.

I also switched back to my WiFi but was on a hot spot.

I solved this by clean swiping the emulator. Restore to factory settings. Then re-running visual studio xamarin app which wil redeploy your app again to the fresh emulator.

It worked. I thought I was going to battle for days to solve this. Luckily this post pointed me in the right direction.

I could not understand how it worked perfectly before and then stopped with no code change.

This is my code for reference:

using var response = await httpClient.GetAsync(sb.ToString());
string apiResponse = await response.Content.ReadAsStringAsync();

I encountered this error when running my Android app on my home WiFi, then trying to run it on different WiFi without closing my simulator.

Simply closing the simulator and re-launching the app worked for me!


I had the same problem, but with small difference. I had added NetworkConnectionCallback to check situation when internet connection had changed at runtime, and checking like this before sending all requests:

private fun isConnected(): Boolean {
    val activeNetwork = cManager.activeNetworkInfo
    return activeNetwork != null && activeNetwork.isConnected
}

There can be state like CONNECTING (you can see i? when you turn on wifi, icon starts blinking, after connecting to network, image is static). So, we have two different states: one CONNECT another CONNECTING, and when Retrofit tried to send request internet connection is disabled and it throws UnknownHostException. I forgot to add another type of exception in function which was responsible for sending requests.

try{
//for example, retrofit call
}
catch (e: Exception) {
        is UnknownHostException -> "Unknown host!"
        is ConnectException -> "No internet!"
        else -> "Unknown exception!"
    }

It's just a tricky moment that can by related with this problem.

Hope, I will help somebody)


I was having the same issue, but with Glide. When I was going to disconnect from wifi and reconnect (just like it was suggested here), I noticed that I was in Airplane mode ???


I was testing my application with the Android emulator and I solved this by turning off and turning on the Wi-Fi on the Android emulator device! It worked perfectly.


I had the same exception in the simulator (Android Studio on OSX) but connecting to the same URL on the iOS simulator worked fine... Looks like it all stemmed from the fact I'd be running the simulator whilst connected to a personal hotspot for my internet connection and then came back later while connected to wifi and the simulator didn't like the new internet connection for some reason, seems like it thought the old hotspot was the current connection, which was no longer working..

Closing and relaunching the simulator worked!


I got the same error and the issue was that I was on VPN and I didn't realize it. After disconnecting from the VPN and reconnecting to my WIFI network, the problem was resolved.


If reconnecting the WiFi doesn't work for you, try reboot your device.

This works for me. Hope it helps.


I had this issue on Android 10,

Changed targetSdkVersion 29 to targetSdkVersion 28 issue resolved. Not sure what is the actual problem.

I think not a good practice, but it worked.

before:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 29

Now:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 28


Missed to configure tag in manifest file

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to android-asynctask

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Android check null or empty string in Android java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState Android basics: running code in the UI thread How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? Android. Fragment getActivity() sometimes returns null android asynctask sending callbacks to ui AsyncTask Android example Return a value from AsyncTask in Android