1

In C# code we are using network authentication:

req = HttpWebRequest.Create(Url)
req.Method = "POST"
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate")
req.Credentials = New NetworkCredential(Username, Password)

We need to implement same in Java. I have tried folowing two approach but it is not working:

  1. httppost.setHeader("Authorization", "Basic " + "username:password");

  2. Authenticator.setDefault(new PaswordAuthentication());

but both did not work. Any lead will be highly appreciated.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
Rakesh
  • 109
  • 2
  • 9

2 Answers2

1

Although the following link answers the question it does not show a full solution using HttpClientBuilder. Here is the full sample that gets the index file from an IIS server requiring Windows Authentication.

package test;

import java.util.*;

import org.apache.http.*;
import org.apache.http.auth.*;
import org.apache.http.client.*;
import org.apache.http.client.config.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.util.*;

public class Test 
{
    public static void main(String[] args)
    {
        try
        {
            RequestConfig requestConfig = RequestConfig.custom()
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM))
                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
                .build();

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials("USERNAME", "PASSWORD", "HOSTNAME", "DOMAIN"));

            HttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credentialsProvider)
                .setDefaultRequestConfig(requestConfig)
                .build();

            HttpHost target = new HttpHost("localhost", 80, "http");
            HttpGet httpget = new HttpGet("/");
            HttpResponse r = httpclient.execute(target, httpget);
            HttpEntity e = r.getEntity();
            String responseString = EntityUtils.toString(e, "UTF-8");
            System.out.println(responseString);
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}
Community
  • 1
  • 1
Mike
  • 559
  • 5
  • 21
0

Have you tried org.apache.commons.httpclient.NTCredentials?

Here's a link to some samples.

Mike
  • 559
  • 5
  • 21
  • Hi Mike How to use NTCredentials with HttpClient? defaulthhtpclient are depreciated now. – Rakesh Sep 16 '15 at 03:00
  • I haven't used it, but according to the documentation you should use HttpClientBuilder instead. – Mike Sep 16 '15 at 18:51