简体   繁体   中英

How to fix the UnknownHostException in java

I am trying to access the HP ALM rest api to get the login authentication tokens using java but the rest api throws UnknownHostException.

private static final String almURL = "https://myalmUrl.com/qcbin";
private static final String isAuthenticatedPath = "authentication-point/authenticate";
public static String strUserName = "username";
public static String strPassword = "password";

    private static String getEncodedAuthString() {
            String auth = strUserName + ":" + strPassword;
            byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes());
            String authHeader = "Basic " + new String(encodedAuth);
            return authHeader;
        }

    public static void main(String args[]) {
            client = ClientBuilder.newBuilder().build();
            target = client.target(almURL).path(isAuthenticatedPath);
            invocationBuilder = target.request(new String[] { "application/xml" });
            invocationBuilder.header("Authorization", getEncodedAuthString());
            res = invocationBuilder.get(); // error occured
    }

error : Exception in thread "main" javax.ws.rs.ProcessingException: java.net.UnknownHostException: myalmUrl.com

What is the problem in this code? how can i fix it?

Reason: Usually the UnknownHostException fires when you cannot resolve the DNS record of the URL you've provided. There's a reasonable timeout for that operation, but if you have a weak Wi-Fi connection or you don't have enough signal on your device, the communication can be interrupted in the middle between sending a request and receiving a response, so your device doesn't receive a response, thus it thinks it's a DNS timeout.

Long story short, there are two main reasons for an exception:

  1. If your Wi-Fi signals are weak.
  2. If your device connected to the Wi-Fi but no internet is not available.

Solution: Before request check availability of the internet using HttpURLConnection class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM