简体   繁体   中英

REST Client returns HTTP response code: 401

Thanks for your time!

Setup: I've written a JAVA REST client which authenticates (with username/password) and returns a JSON.

Problem:

This is the exception that I'm getting:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: https://1.1.1.1/api/count

Code:

public class AnotherDemo {
    static {
        //for localhost testing only
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
        new javax.net.ssl.HostnameVerifier(){

            public boolean verify(String hostname,
                    javax.net.ssl.SSLSession sslSession) {
                if (hostname.equals("localhost")) {
                    return true;
                }
                return false;
            }
        });
    }
    public static void main(String[] args) throws Exception{

           TrustManager[] trustAllCerts = new TrustManager[] {
                   new X509TrustManager() {
                      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                      }

                      public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

                      public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

                   }
                };

                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                      return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        String urlString = "https://1.1.1.1/api/count";
        String username = "admin";
        String password = "admin";

        String usercredentials = username+":admin"+password;
        String basicAuth = "Basic"+ new String (new Base64().encode(usercredentials.getBytes())); 

        // pass encoded user name and password as header
        URL url = new URL(urlString);
//      URLConnection conn = url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Basic " + basicAuth);
        conn.setRequestProperty("Accept", "application/json");
        BufferedReader r = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line = r.readLine();
        while (line != null) {
            System.out.println(line);
            line = r.readLine();
        }
    }
}

Can someone tell me what I'm doing wrong?

If I use POSTMAN, everything works fine! I get the JSON!

Thanks, R

Managed to resolve this question. These are the issues:

This line needs to be corrected and also

String usercredentials = username+":admin"+password;
 String basicAuth = "Basic"+ new String (new Base64().encode(usercredentials.getBytes())); 

to

String usercredentials = username+":"+password;
String basicAuth = "Basic"+ new String (new Base64().encode(usercredentials.getBytes())); 

Also, for the issues with SSL handler or this exception,

com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Please add the following LOC:

   TrustManager[] trustAllCerts = new TrustManager[] {
           new X509TrustManager() {
              public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
              }

              public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

              public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

           }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        /*
         * end of the fix
         */

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