有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java REST客户端返回HTTP响应代码:401

谢谢你的时间

设置: 我已经编写了一个JavaREST客户端,它进行身份验证(使用用户名/密码)并返回一个JSON

问题:

这是我得到的一个例外:

线程“main”java中出现异常。木卫一。IOException:服务器为URL返回了HTTP响应代码401:https://1.1.1.1/api/count

代码:

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

有人能告诉我我做错了什么吗

如果我使用邮递员,一切正常!我明白了

谢谢, R


共 (1) 个答案

  1. # 1 楼答案

    设法解决了这个问题。这些问题是:

    这条线需要修正,也需要修正

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

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

    另外,对于SSL处理程序的问题或此异常

    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
    

    请添加以下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
             */