Reputation: 109
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:
httppost.setHeader("Authorization", "Basic " + "username:password");
Authenticator.setDefault(new PaswordAuthentication());
but both did not work. Any lead will be highly appreciated.
Upvotes: 1
Views: 5183
Reputation: 559
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());
}
}
}
Upvotes: 1
Reputation: 559
Have you tried org.apache.commons.httpclient.NTCredentials?
Here's a link to some samples.
Upvotes: 0