Java net unknownhostexception как исправить

What are the steps I should take to solve the error:

java.net.UnknownHostException: Invalid hostname for server: local

I added the new virtual host name at Android emulator but the result returns to

 java.net.UnknownHostException virtualhostname at 
  java.net.InetAddress.lookUpHostByName(InetAddress.java:506)

When I type my virtualhost URL on my PC, it works on display. Then again, when I ran on Emulator and check on Logcat, I couldn’t be able to read or check the HTTP status if 200, 202, or an error code number. It simply returned to UnknownHostException

Bruno Bieri's user avatar

Bruno Bieri

9,60411 gold badges63 silver badges90 bronze badges

asked Jun 26, 2011 at 13:34

Ashish Agarwal's user avatar

Ashish AgarwalAshish Agarwal

14.4k31 gold badges84 silver badges124 bronze badges

3

I was having the same issue on my mac. I found the issue when I pinged my $HOSTNAME from terminal and it returned ping: cannot resolve myHostName: Unknown host.

To resolve:

  1. Do echo $HOSTNAME on your terminal.

  2. Whatever hostname it shows (lets say myHostName), try to ping it : ping myHostName. If it returns ping: cannot resolve myHostName: Unknown host then add an entry into your /etc/hosts file.

  3. For that edit /etc/hosts file and add following:

    127.0.0.1 myHostName

Chaminda Bandara's user avatar

answered Nov 1, 2014 at 4:42

Shobhit Puri's user avatar

Shobhit PuriShobhit Puri

25.7k11 gold badges94 silver badges123 bronze badges

2

What the exception is really saying is that there is no known server with the name “local”. My guess is that you’re trying to connect to your local computer. Try with the hostname "localhost" instead, or perhaps 127.0.0.1 or ::1 (the last one is IPv6).

From the javadocs:

Thrown to indicate that the IP address
of a host could not be determined.

127.0.0.1or ::1 or "localhost" should always be the loopback interface, so if that doesn’t work I’d be really surprised.

If there really is a server called “local” on your network – examine your DNS settings or add it to your hosts file.

rogerdpack's user avatar

rogerdpack

61.9k36 gold badges265 silver badges386 bronze badges

answered Jun 26, 2011 at 13:37

André Laszlo's user avatar

1

java.net.UnknownHostException: Host is unresolved:

Thrown to indicate that the IP address of a host could not be determined.

This exception is also raised when you are connected to a valid wifi but router does not receive the internet. Its very easy to reproduce this:

  1. Connect to a valid wifi
  2. Now remove the cable from the router while router is pluged-in

You will observe this error!!

You can’t really solve this, You can only notify the user gracefully. (something like – “Unable to make a connection”)

answered Sep 19, 2012 at 21:32

Ash's user avatar

AshAsh

1,38115 silver badges20 bronze badges

5

This is not specific to the question, but this question showed up when I was Googling for the mentioned UnknownHostException, and the fix is not found anywhere else so I thought I’d add an answer here.

The exception that was continuously received was:

java.net.UnknownHostException:  google.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    ... 

No matter how I tried to connect to any valid host, printing it in the terminal would not help either. Everything was right.

The Solution

Not calling trim() for the host string which contained whitespace. In writing a proxy server the host was obtained from HTTP headers with the use of split(":") by semicolons for the HOST header. This left whitespace, and causes the UnknownHostException as a host with whitespace is not a valid host. Doing a host = host.trim() on the String host solved the ambiguous issue.

answered Nov 29, 2015 at 7:51

matrixanomaly's user avatar

matrixanomalymatrixanomaly

6,5472 gold badges35 silver badges58 bronze badges

2

Your hostname is missing. JBoss uses this environment variable ($HOSTNAME) when it connects to the server.

[root@xyz ~]# echo $HOSTNAME
xyz

[root@xyz ~]# ping $HOSTNAME
ping: unknown host xyz

[root@xyz ~]# hostname -f
hostname: Unknown host

There are dozens of things that can cause this. Please comment if you discover a new reason.

For a hack until you can permanently resolve this issue on your server, you can add a line to the end of your /etc/hosts file:

127.0.0.1 xyz.xxx.xxx.edu xyz

answered Dec 4, 2015 at 18:11

Entree's user avatar

EntreeEntree

18.2k38 gold badges159 silver badges242 bronze badges

1

This might happen due to various reasons

1) Check if you have VPN connected, you might get this error sometimes if yes

“Your hostname, localhost resolves to a loopback address: 127.0.0.1; using 10.xxx.1.193 instead (on interface cscotun0)”

2) Check your $HOSTNAME

3) try to ping $HOSTNAME on commandline and if it doesnt work, tweak the system settings to make your local host respond to pings

answered May 28, 2014 at 14:45

Sidharth N. Kashyap's user avatar

Try the following :

String url = "http://www.google.com/search?q=java";
URL urlObj = (URL)new URL(url.trim());
HttpURLConnection httpConn = 
(HttpURLConnection)urlObj.openConnection();
httpConn.setRequestMethod("GET");
Integer rescode = httpConn.getResponseCode();
System.out.println(rescode);

Trim() the URL

answered Feb 7, 2018 at 10:36

rex roy's user avatar

rex royrex roy

1,00112 silver badges5 bronze badges

1

Trying to connect to your local computer.try with the hostname “localhost” instead or perhaps ::/ – the last one is ipv6

Volker E.'s user avatar

Volker E.

5,87111 gold badges47 silver badges64 bronze badges

answered May 22, 2013 at 6:47

joshwayne diestro's user avatar

Please try to set SPARK_LOCAL_IP environment variable to the ip address(can be localhost i.e. your own ip address) you want to connect. E.g.

$ export SPARK_LOCAL_IP=182.95.208.152

This way you will not be required to alter existing linux settings.
Worked for me, hope helps you too.

answered Sep 21, 2016 at 5:06

Jyoti Gupta's user avatar

0

Connect your mobile with different wifi connection with different service provider.
I don’t know the exact issue but i could not connect to server with a specific service provider but it work when i connected to other service provider. So try it!

answered Aug 20, 2018 at 6:44

Suraj Vaishnav's user avatar

Suraj VaishnavSuraj Vaishnav

7,6274 gold badges43 silver badges46 bronze badges

I had this issue in my android app when grabbing an xml file the format of my link was not valid, I reformatted with the full url and it worked.

answered Sep 15, 2019 at 19:37

vasmos's user avatar

vasmosvasmos

2,4721 gold badge10 silver badges21 bronze badges

If you are here because your emulator gives you that Exception, Go to Tools > AVD Manager in your android emulator and Cold boot your Emulator.

answered Nov 3, 2019 at 17:42

Favour Felix Chinemerem's user avatar

I had the same issue.

Restart docker was the fix for me. For some reason it needed a restart, I don´t know why, but it worked.

answered Jun 20, 2022 at 9:09

David Marciel's user avatar

David MarcielDavid Marciel

8491 gold badge12 silver badges29 bronze badges

If your /etc/localhosts file has entry as below:
Add hostname entry as below:

127.0.0.1 local host (add your hostname here)
::1 (add hostname here) (the last one is IPv6).

This should resolve the issue.

Floern's user avatar

Floern

33.4k24 gold badges104 silver badges119 bronze badges

answered Jul 18, 2017 at 17:20

user8326951's user avatar

  connection successful
    {
    "AllMenu": [{
        "0": "3",
        "menu_id": "3",
        "1": "Aloo Parathas",
        "name": "Aloo Parathas",
        "2": "170",
        "price": "170",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/1.jpg",
        "image_path": "http://mahatiffin.com/uploads/1.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "7",
        "menu_id": "7",
        "1": "ZzaxZxszsc",
        "name": "ZzaxZxszsc",
        "2": "343",
        "price": "343",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/2.jpg",
        "image_path": "http://mahatiffin.com/uploads/2.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "8",
        "menu_id": "8",
        "1": "sdcsdvsd",
        "name": "sdcsdvsd",
        "2": "435",
        "price": "435",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/3.jpg",
        "image_path": "http://mahatiffin.com/uploads/3.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "9",
        "menu_id": "9",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "435",
        "price": "435",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/4.jpg",
        "image_path": "http://mahatiffin.com/uploads/4.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "10",
        "menu_id": "10",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "456",
        "price": "456",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/5.jpg",
        "image_path": "http://mahatiffin.com/uploads/5.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "11",
        "menu_id": "11",
        "1": "sda",
        "name": "sda",
        "2": "234",
        "price": "234",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/6.JPG",
        "image_path": "http://mahatiffin.com/uploads/6.JPG",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "12",
        "menu_id": "12",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "324",
        "price": "324",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/7.JPEG",
        "image_path": "http://mahatiffin.com/uploads/7.JPEG",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "14",
        "menu_id": "14",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "232",
        "price": "232",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/1.jpg",
        "image_path": "http://mahatiffin.com/uploads/1.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "15",
        "menu_id": "15",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "325",
        "price": "325",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/2.jpg",
        "image_path": "http://mahatiffin.com/uploads/2.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "16",
        "menu_id": "16",
        "1": "sadcasc",
        "name": "sadcasc",
        "2": "344",
        "price": "344",
        "3": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "Description": "fjhsjfh jfhrwkjfh wejfhwkh ewjfhwjeh ewjfhkwe ewbfjeh wejhfkjwhhef ehfkwh wewjrh",
        "4": "http://mahatiffin.com/uploads/4.jpg",
        "image_path": "http://mahatiffin.com/uploads/4.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "1",
        "type_id": "1"
    }, {
        "0": "18",
        "menu_id": "18",
        "1": "edfwdfewr",
        "name": "edfwdfewr",
        "2": "23",
        "price": "23",
        "3": "xasx scasc dqedqd edbhwd dwh3ej1 1wh1e2ue 3eh3ue e2euh23ueej ewnwencj",
        "Description": "xasx scasc dqedqd edbhwd dwh3ej1 1wh1e2ue 3eh3ue e2euh23ueej ewnwencj",
        "4": "http://mahatiffin.com/uploads/4.jpg",
        "image_path": "http://mahatiffin.com/uploads/4.jpg",
        "5": "Regular-menu",
        "menu_cat": "Regular-menu",
        "6": "2",
        "type_id": "2"
    }, {
        "0": "19",
        "menu_id": "19",
        "1": "Aloo Gobi",
        "name": "Aloo Gobi",
        "2": "250",
        "price": "250",
        "3": "Aloo Sabzi, 2 Puris, Rice, Dal, Shrikhand",
        "Description": "Aloo Sabzi, 2 Puris, Rice, Dal, Shrikhand",
        "4": "http://mahatiffin.com/uploads/1.jpg",
        "image_path": "http://mahatiffin.com/uploads/1.jpg",
        "5": "Special-menu",
        "menu_cat": "Special-menu",
        "6": "1",
        "type_id": "1"
    }]
}

Remove String “connection successful” from Php Json at start of the page.

2) Problem Class cast exception: change as bellow :

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.all_item_layout, container, false);
        itemlist = new ArrayList<HashMap<String, String>>();
        new ReadJSON().execute();
        list = (ListView) view.findViewById(android.R.id.list);

        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(getActivity(), itemlist);
        // Set the adapter to the ListView
        list.setAdapter((ListAdapter) adapter);
        return view;
    }

and

@Override
        protected void onPostExecute(Void args) {
          adapter.notifydatasetchanged();
        }

and

remove ” itemlist = new ArrayList>(); ” from doInBackground() method.

Автор оригинала: baeldung.

1. введение

В этом уроке мы узнаем причину UnknownHostException на примере. Мы также обсудим возможные способы предотвращения и обработки исключения.

2. Когда Возникает исключение?

UnknownHostException указывает, что IP – адрес имени хоста не может быть определен. Это может произойти из-за опечатки в имени хоста:

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

Приведенный выше код вызывает исключение UnknownHostException , поскольку неправильно написанный localhost не указывает ни на какие IP-адреса.

Еще одна возможная причина UnknownHostException это задержка распространения DNS или неправильная конфигурация DNS.

Для распространения новой записи DNS по всему Интернету может потребоваться до 48 часов.

3. Как Это предотвратить?

Предотвращение возникновения исключения в первую очередь лучше, чем последующая обработка. Несколько советов по предотвращению исключения:

  1. Дважды проверьте имя хоста: Убедитесь, что нет опечатки, и обрежьте все пробелы.
  2. Проверьте настройки DNS системы: Убедитесь, что DNS-сервер включен и доступен, и если имя хоста новое, дождитесь, пока DNS-сервер догонит вас.

4. Как с Этим справиться?

UnknownHostException расширяет IOException , которое является проверенным исключением . Как и любое другое проверенное исключение, мы должны либо выбросить его, либо окружить блоком try-catch .

Давайте рассмотрим исключение в нашем примере:

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

Рекомендуется закрывать соединение при возникновении UnknownHostException . Большое количество расточительных открытых соединений может привести к тому, что приложению не хватит памяти.

5. Заключение

В этой статье мы узнали, что вызывает UnknownHostException , как его предотвратить и как с ним справиться.

Как всегда, код доступен на Github .


  • Метки


    exception, hostname, server, unknownhostexception

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.

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

Photo of Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

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

Добавить комментарий