简体   繁体   中英

Java - Http Authentification 401 error with HttpClient library

登录窗口

This dialog appears when I try to login from web browser (IE, Chromw, Etc).

Using Apache httpclient library try to auto-login.

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

way 2. Using Apache HttpClient QuickStart Example (X)

All of the above methods does not work.

Please Help me.

Lastest Try Code

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

Console window says:

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

This Code work for me.

Main Issue occured by Base64 (apache-commons-codec). So, I Change that Base64 encoder to sun.misc.BASE64EnCoder and It's working like a magic.

Lastest Working Code.

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.");
}

And Console window finally say:

HTTP/1.0 200 OK

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