1

我正在尝试编写一个连接到启用 kerberos 的 tomcat 的 http 客户端(使用浏览器测试是正确的)。它首先获取响应代码(将是 401),然后继续其工作。

代码是

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;

public class SampleHTTP2 {

    static final String kuser = "correctusername"; // your account name
    static final String kpass = "correctpassword"; // your password for the account

    static class MyAuthenticator extends Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            //System.out.println("I am reaching here");
            // I haven't checked getRequestingScheme() here, since for NTLM
            // and Negotiate, the username and password are all the same.
            System.err.println("Feeding username and password for "
               + getRequestingScheme());
            return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
    }

    public static void main(String[] args) throws Exception {

        URL url = new URL("http://mycompname:6008/examples/");
        HttpURLConnection h1 = (HttpURLConnection) url.openConnection();

        int rescode = h1.getResponseCode();

        System.out.println(rescode);
        System.setProperty("sun.security.krb5.debug", "true");
        System.setProperty("java.security.auth.login.config", "C:\\login2.conf");
        System.setProperty("javax.security.auth.useSubjectCredsOnly","false");

        System.setProperty("java.security.krb5.conf", "C:\\krb5.ini");
        if(rescode == 401){     
            Authenticator.setDefault(new MyAuthenticator());

            URL url2 = new URL("http://mycompname/examples/");
            URLConnection h2 = url2.openConnection();
            InputStream ins2 = h2.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(ins2));
            String str;
            while((str = reader.readLine()) != null)
                System.out.println(str);
        }
    }
}

现在,当我评论该行时:-

 int rescode = h1.getResponseCode();

并输入 if(true) 而不是 if(rescode ==401),它可以工作。

我不确定出了什么问题。getResponseCode() 在内部调用 getinputStream ,因此我使用了单独的 url 连接。即使它仍然不起作用

PS - 服务器设置完美,Authenticator 类也是正确的。

4

0 回答 0