Error java net unknownhostexception unable to resolve host

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 ...

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)

In my Android application for reading RSS links, I am getting this error:

java.net.UnknownHostException:
Unable to resolve host «example.com»;
No address associated with hostname.

In my emulator I can connect to Google through a browser.
Please help me to resolve this issue.

Community's user avatar

asked Jun 15, 2011 at 9:14

bejoy george's user avatar

10

You probably don’t have the INTERNET permission. Try adding this to your AndroidManifest.xml file, right before </manifest>:

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

Note: the above doesn’t have to be right before the </manifest> tag, but that is a good / correct place to put it.

Note: if this answer doesn’t help in your case, read the other answers!

Stephen C's user avatar

Stephen C

688k94 gold badges790 silver badges1200 bronze badges

answered Jun 15, 2011 at 9:57

Felix's user avatar

FelixFelix

87.8k43 gold badges149 silver badges167 bronze badges

4

I’ve seen this problem in the emulator as well. In my case, it is caused by launching the emulator, then putting the computer to sleep or changing the network connection (going from work to home, etc), then attempting to use the same emulator again. Closing and re-launching the emulator resolves the problem in this case.

answered May 10, 2013 at 17:20

Eric Brynsvold's user avatar

Eric BrynsvoldEric Brynsvold

2,7603 gold badges17 silver badges22 bronze badges

7

It is WiFi bug due to wifi disable or not properly connected.

Simply Reconnect the wifi will solve the issue.

answered Jul 6, 2015 at 9:29

shehzy's user avatar

shehzyshehzy

2,1453 gold badges24 silver badges43 bronze badges

Unable to resolve host “”; No address associated with hostname

you must have to check below code here on your manifest :

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

and most important at least for me:-

enabled wifi connection or internet connection on your mobile device

Brandon Minnick's user avatar

answered Jun 17, 2013 at 5:51

duggu's user avatar

dugguduggu

37.6k12 gold badges115 silver badges112 bronze badges

2

Sometimes, although you add <uses-permission android:name="android.permission.INTERNET" /> in the AndroidManifest and you have a WiFi connection, this exception can be thrown. In my case, I have turned off WiFi and then turned it on again. This resolved the error. Weird solution, but sometimes it works.

Jared Rummler's user avatar

Jared Rummler

37.5k19 gold badges134 silver badges147 bronze badges

answered Jun 30, 2014 at 6:37

Batuhan Coşkun's user avatar

Batuhan CoşkunBatuhan Coşkun

2,9432 gold badges30 silver badges48 bronze badges

2

Check you have:

1- Access to Internet connectivity.

2- The permission for internet is present in the manifest.

3- The url host is valid and registered in a trusted domain name server.

answered Apr 15, 2018 at 1:48

Pablo Valdes's user avatar

"" it seems you are trying to resolve this host , which is invalid.

Check for rss URL

Update
Following are the possibilities

1 Your browser is configured with proxy, app not

System.setProperty("http.proxyHost", "my.proxyhost.com");
System.setProperty("http.proxyPort", "1234");

2 Your browser has access to internet. not app

3 can be an SSL issue if URL is secured

answered Jun 15, 2011 at 9:16

jmj's user avatar

jmjjmj

236k42 gold badges397 silver badges435 bronze badges

9

I had the same issue. My virtual device was showing a crossed-out WiFi icon at the top bar of the device. I rebooted the virtual device and everything was back to normal.

Robert Columbia's user avatar

answered Apr 24, 2018 at 1:29

Fo Nko's user avatar

Fo NkoFo Nko

5969 silver badges21 bronze badges

Some times on the emulator, I have to launch the browser before my app can access the Internet.

Robert Columbia's user avatar

answered Jun 15, 2011 at 11:48

Snicolas's user avatar

SnicolasSnicolas

37.7k15 gold badges113 silver badges172 bronze badges

1

It could be due to below reasons: —

  1. Either you dont have INTERNET permission in manifest file. If so then please use this statement <uses-permission android:name="android.permission.INTERNET" />

  2. Or you are connected to a network but your internet connection is not working. Like you are connected to a Wi-Fi but it doesnt have internet connection or Mobile data on your phone is ON but you dont have data connectivity on your phone.

Point# 2 is interesting and its not assumption, I have tested the same at my end.

Hope this will help you

Summved

answered Feb 23, 2017 at 10:27

Summved Jain's user avatar

Summved JainSummved Jain

8622 gold badges18 silver badges21 bronze badges

In my case, I had that error when I’m connected to VPN on my host but not on simulator. Turning the VPN off solved the issue

answered Jun 27, 2017 at 11:42

William Kinaan's user avatar

William KinaanWilliam Kinaan

27.6k20 gold badges84 silver badges118 bronze badges

In my case problem was with WIFI working with IPV6 and my domain did not have IPv6 adress

answered Dec 4, 2017 at 12:16

Paweł Rutkowski's user avatar

1

It’s not your fault bae, I’ve had this happen sometimes when the emulator’s in a weird state. Just restarting the emulator helped me.

answered Feb 10, 2016 at 0:55

Ed Lee's user avatar

Ed LeeEd Lee

1772 silver badges13 bronze badges

If you are running the app on an emulator, make sure that it is properly connected to the internet. If it is not, the easiest way of solving it is reopening the emulator or creating a new device.

answered Jan 15, 2015 at 11:47

Alex Styl's user avatar

Alex StylAlex Styl

3,7432 gold badges27 silver badges44 bronze badges

I Had the same problem, and it was because the simulator somehow got in airplane mode, once this was disabled my App worked fine :-)
I had tried everything, rebuild, clean+build and reboot android studio and reboot the computer, even reinstalling android studio..

answered Dec 13, 2016 at 7:37

TWOcvfan's user avatar

TWOcvfanTWOcvfan

3371 gold badge3 silver badges18 bronze badges

Check permission for INTERNET in mainfest file and check network connectivity.

answered Sep 21, 2016 at 18:49

Chetan Chaudhari's user avatar

1. Introduction

In this tutorial, we’ll learn the cause of UnknownHostException with an example. We’ll also discuss possible ways of preventing and handling the exception.

2. When Is the Exception Thrown?

UnknownHostException indicates that the IP address of a hostname could not be determined. It can happen because of a typo in the hostname:

String hostname = "http://locaihost";
URL url = new URL(hostname);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.getResponseCode();

The above code throws an UnknownHostException since the misspelled locaihost doesn’t point to any IP addresses.

Another possible reason for UnknownHostException is DNS propagation delay or DNS misconfiguration.

It might take up to 48 hours for a new DNS entry to be propagated all around the Internet.

3. How to Prevent It?

Preventing the exception from occurring in the first place is better than handling it afterward. A few tips to prevent the exception are:

  1. Double-check the hostname: Make sure there is no typo, and trim all whitespaces.
  2. Check the system’s DNS settings: Make sure the DNS server is up and reachable, and if the hostname is new, wait for the DNS server to catch up.

4. How to Handle It?

UnknownHostException extends IOException, which is a checked exception. Similar to any other checked exception, we must either throw it or surround it with a try-catch block.

Let’s handle the exception in our example:

try {
    con.getResponseCode();
} catch (UnknownHostException e) {
    con.disconnect();
}

It’s a good practice to close the connection when UnknownHostException occurs. A lot of wasteful open connections can cause the application to run out of memory.

5. Conclusion

In this article, we learned what causes UnknownHostException, how to prevent it, and how to handle it.

As always, the code is available over on Github.

In this tutorial we are going to talk about java.net.UnknownHostException. This is a subclass of IOException, so it is a checked exception. It emerges when you are trying to connect to a remote host using its host name, but the IP address of that host cannot be resolved. So, this a straight forward situation.

1. A simple Client-Server application

To demonstrate this exception, I’m going to use the client-server application we’ve seen in java.net.ConnectException – How to solve Connect Exception. It creates two threads. The first one, SimpleServer, opens a socket on the local machine on port 3333. Then it waits for a connection to come in. When it finally receives a connection, it creates an input stream out of it, and simply reads one line of text from the client that was connected. The second thread, SimpleClient, attempts to connect to the server socket that SimpleServer opened. When it does so, it sends a line of text and that’s it.

UnknownHostExceptionExample.java:

package com.javacodegeeks.core.net.unknownhostexception;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class UnknownHostExceptionExample {

	public static void main(String[] args) {

		new Thread(new SimpleServer()).start();
		new Thread(new SimpleClient()).start();

	}

	static class SimpleServer implements Runnable {

		@Override
		public void run() {

			ServerSocket serverSocket = null;
			while (true) {
				
				try {
					serverSocket = new ServerSocket(3333);

					Socket clientSocket = serverSocket.accept();

					BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
					
					System.out.println("Client said :"+inputReader.readLine());

				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						serverSocket.close();
					
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}

	}

	static class SimpleClient implements Runnable {

		@Override
		public void run() {

			Socket socket = null;
			try {
				Thread.sleep(3000);
				
				socket = new Socket("localhost", 3333);
				
			    PrintWriter outWriter = new PrintWriter(socket.getOutputStream(),true);
			    
			    outWriter.println("Hello Mr. Server!");
			   

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				
				try {
					socket.close();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			}
		}

	}
}

As you can see, because I’m launching the two threads simultaneously, I’ve put a 3 second delay in SimpleClient for the client to wait before attempting to connect to the server socket, so as to give some time to server thread to open the server socket.

If you run the above program, after 3 seconds you will see an output like this :

Client said :Hello Mr. Server!

That means that the client, successfully connected to the server and achieved to transmit its text.

2. An example of UnknownHostException

Let’s see what happens when we change :

socket = new Socket("localhost", 3333);

to

socket = new Socket("local", 3333);

If you run the program again, this is the output:

java.net.UnknownHostException: local
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.net.Socket.connect(Socket.java:579)
	at java.net.Socket.connect(Socket.java:528)
	at java.net.Socket.<init>(Socket.java:425)
	at java.net.Socket.<init>(Socket.java:208)
	at com.javacodegeeks.core.net.unknownhostexception.UnknownHostExceptionExample$SimpleClient.run(UnknownHostExceptionExample.java:64)
	at java.lang.Thread.run(Thread.java:744)

As you can see the IP address of the host "local" cannot be resolved, so an UnknownHostException is thrown.

3. How to solve UnknownHostException

UnknownHostException designates a pretty straight forward problem. That the IP address of the remote host you are trying to reach cannot be resolved. So the solution to this is very simple. You should check the input of Socket (or any other method that throws an UnknownHostException), and validate that it is the intended one. If you are not whether you have the correct host name, you can launch a UNIX terminal and use the nslookup command (among others) to see if your DNS server can resolve the host name to an IP address successfully. Here is an example :

nikos@nikos:~$ nslookup www.google.com
Server:		127.0.1.1
Address:	127.0.1.1#53

Non-authoritative answer:
Name:	www.google.com
Address: 173.194.39.209
Name:	www.google.com
Address: 173.194.39.210
Name:	www.google.com
Address: 173.194.39.212
Name:	www.google.com
Address: 173.194.39.211
Name:	www.google.com
Address: 173.194.39.208

nikos@nikos:~$ 

If you are on Windows you can use the host command. If that doesn’t work as expected then, you should check if the host name you have is correct and then try to refresh your DNS cache. If that doesn’t work either, try to use a different DNS server, eg Google Public DNS is a very good alternative.

Download Source Code

This was an example on java.net.UnknownHostException and how to solve UnknownHostException. You can download the source code of this example here : UnknownHostExceptionExample.zip

A quick guide to An UnknownHostException and it is thrown if a java.net.UnknownHostException occurs while creating a connection to the remote host for a remote method call. Preventive ways to UnknownHostException.

1. Introduction

In this tutorial, We’ll learn what is UnknownHostException and What is the cause to produce it. And also learn how to prevent it.  UnknownHostException is a common exception and will show the best ways to prevent this exception.

Hierarchy:

java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.rmi.RemoteException
java.rmi.UnknownHostException

2. When is the Exception Thrown?

UnknownHostException is thrown if and if only there was a problem with a domain name or mistake in typing. And also indicates that the IP Address of a website could not be determined.

package com.java.w3schools.blog.exceptions;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UnknownHostExceptionException {

 public static void main(String[] args) throws IOException {

  String hostname = "http://javaprogram.comm";
  URL url = null;
  try {
   url = new URL(hostname);
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
  con.getResponseCode();

 }

}

Output:

Exception in thread "main" java.net.UnknownHostException: javaprogram.comm
 at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:220)
 at java.base/java.net.Socket.connect(Socket.java:591)
 at java.base/java.net.Socket.connect(Socket.java:540)
 at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
 at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
 at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
 at java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
 at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:341)
 at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:362)
 at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1242)
 at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1181)
 at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1075)
 at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1009)
 at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1581)
 at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
 at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527)
 at com.java.w3schools.blog.exceptions.UnknownHostExceptionException.main(UnknownHostExceptionException.java:21)

In the above program by mistakenly, added comm instead of com. Because this, it generated error.

3. How to Prevent It?

Prevention is better than cure. Always prevention comes in the first place rather than facing the problem.

Below are important tips to prevent.

Double-check hostname — It is good to check the spelling of the domain and trim the extra spaces.
Check DNS Settings — Ensure that the DNS server is up and running using ping hostname command from your machine before running the application. If the hostname is new then wait for some time to DNS server to be reachable.

4. How to Handle?

UnknownHostException extends IOException, which is a checked exception. Similar to any other checked exception, we must either throw it or surround it with a try-catch block.

Let’s handle the exception in our example:

try {
    con.getResponseCode();
} catch (UnknownHostException e) {
    con.disconnect();
}

Thread.sleep(5000) — Sleep for some time then retry. This should resolve the problem if there is a network issue. Instead of sleep don’t use interrupted() method.

It’s a good practice to close the connection when UnknownHostException occurs. A lot of wasteful open connections can cause(memory leak) the application to run out of memory.

5. Conclusion

In this article, We’ve seen What is UnknownHostException and how to produce and handle it? And also seen the Best ways to prevent it.

GitHub Sample Code

API

The UnknownHostException is an exception in Java that is thrown to indicate that the IP address of a host could not be determined.

Since the UnknownHostException is a checked exception, it either needs to be thrown or surrounded by a try-catch block in code.

What Causes UnknownHostException

The UnknownHostException occurs when trying to connect to a remote host using its hostname, but the IP address of the host could not be determined. This usually happens because of a typo in the hostname, or because of a DNS misconfiguration or propagation delay.

UnknownHostException Example

Here is an example of an UnknownHostException thrown when trying to connect to an unknown host:

public class UnknownHostExceptionExample {
    public static void main(String[] args) {
        String host = "https://rollbar.co";
        URL url = null;

        try {
            url = new URL(host);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            System.out.println(con.getResponseCode());
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

The above code attempts to connect to a remote host, but has a typo in the hostname. Therefore, running the code throws an UnknownHostException exception:

java.net.UnknownHostException: rollbar.co
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:567)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333)
    at java.base/java.net.Socket.connect(Socket.java:648)
    at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:290)
    at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
    at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
    at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:265)
    at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:372)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:177)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1194)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1082)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:163)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1600)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
    at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:308)
    at UnknownHostExceptionExample.main(UnknownHostExceptionExample.java:14)

How to Handle UnknownHostException

Since UnknownHostException is a checked exception, it can be handled by surrounding it with a try-catch block. The earlier example can be updated to handle the exception:

public class UnknownHostExceptionExample {
    public static void main(String[] args) {
        String host = "https://rollbar.co";
        URL url = null;
        HttpURLConnection con = null;

        try {
            url = new URL(host);
            con = (HttpURLConnection) url.openConnection();
            System.out.println(con.getResponseCode());
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (UnknownHostException uhe) {
            uhe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }
}

In the above example, the code that can throw the UnknownHostException is surrounded in a try-catch block. A finally block is also included to close the connection if the UnknownHostException occurs. This is good practice since too many open connections can cause the application to run out of memory.

How to Avoid UnknownHostException

The UnknownHostException can be avoided with the following checks:

  • Valid hostname — The hostname should be double checked to make sure it does not contain any typos or whitespaces.
  • DNS settings — The system DNS settings should be checked to ensure that the DNS server is reachable. If the hostname is new, it may take some time for the DNS server to catch up.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

I use ip address in url and find ‘host’ in header has auto set the ip address by these code in AsyncHttpClient :

 httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
                        ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }
        }, 0);

I need to set host in header then my server can know this request,so I do this in my project:

  client.getHttpContext().setAttribute(ClientContext.TARGET_AUTH_STATE,"test");
  client.addHeader("Host", "xxxhost.com");

Понравилась статья? Поделить с друзьями:
  • Error itoa was not declared in this scope
  • Error iterator should return strings not bytes did you open the file in text mode
  • Error it was not possible to connect hmailserver
  • Error issuing replication 8452 0x2104
  • Error iso image extraction failure