Java net unknownhostexception esia gosuslugi ru

Java UnknownHostException – Invalid Hostname for Server – How to Fix It?

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.

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.

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.getInputStream0(HttpURLConnection.java: 1581 )

at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java: 1509 )

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:

Читайте также:  Интернета index php topic

Источник

java.net.UnknownHostException: Недопустимое имя хоста для сервера

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

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)

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

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

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

Читайте ещё по теме:

Источник

How to Handle the Unknown Host Exception in Java

How to Handle the Unknown Host Exception in Java

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

Источник

Java UnknownHostException — Invalid Hostname for Server — How to Fix It?

Twitter Facebook Google Pinterest

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.

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(); > >
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.(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.

Читайте также:  Какие теги существуют в языке html

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)

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.

Источник

Оцените статью