Java - 与HttpClient库的Http Authentification 401错误

时间:2014-02-11 08:27:43

标签: java apache login apache-httpclient-4.x

login window

当我尝试从Web浏览器(IE,Chromw等)登录时,会出现此对话框。

使用Apache httpclient库尝试自动登录。

方式1. http://userid:pass@hostname (X)

方式2.使用Apache HttpClient快速入门示例(X)

以上所有方法都不起作用。

请帮助我。

最新尝试代码

    DefaultHttpClient httpClient = new DefaultHttpClient();
        try{
            httpClient.getCredentialsProvider()
                .setCredentials(new AuthScope(
                        new HttpHost(host)), 
                        new UsernamePasswordCredentials(username, password));
            HttpGet httpget = new HttpGet(host);
            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }

控制台窗口说:

'executing requestGET http://192.168.100.129/tag/unsubscribe HTTP/1.1'
'----------------------------------------'
'HTTP/1.0 401 Unauthorized'
'Response content length: 0'

1 个答案:

答案 0 :(得分:3)

本准则对我有用。

Base64(apache-commons-codec)发生的主要问题。 所以,我将Base64编码器改为sun.misc.BASE64EnCoder,它就像魔术一样。

最新的工作守则。

String enc = username + ":" + password;

DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
HttpEntity entity;
HttpGet request = new HttpGet(host);

if(checkUserInfo()){
    request.addHeader("Authorization", "Basic " + new BASE64Encoder().encode(enc.getBytes()));
    httpResponse = client.execute(request);
    entity = httpResponse.getEntity();
    System.out.println(httpResponse.getStatusLine());
}else if(!checkUserInfo()){
        throw new Exception("Error :: Must Call setUserInfo(String username, String password) methode firstly.");
}

并且控制台窗口最后说:

HTTP/1.0 200 OK