Java HttpClient with NTLM - how to use default network credentials
Asked Answered
S

1

0

In .NET we can create HttpClient that would use credentials of the current process/user:

var uri = new Uri("http://service-endpoint");
var credentialsCache = new CredentialCache { { uri, "NTLM", CredentialCache.DefaultNetworkCredentials } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
var httpClient = new HttpClient(handler) { BaseAddress = uri, Timeout = new TimeSpan(0, 0, 10) };

Is there an equivalent in Java? I want to be able to send the credentials transparently so the user won't be bothered.

Seagirt answered 11/1, 2022 at 19:30 Comment(0)
S
2

Answering my own question.

It is possible using WinHttpClients from Apache HttpClient 5 https://repo1.maven.org/maven2/org/apache/httpcomponents/client5/httpclient5-win/

import statements:

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.win.WinHttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;

sample request:

public static void Get(String uri) {
        var request = new HttpGet(uri);
        try
        {
            CloseableHttpClient httpClient = WinHttpClients.createDefault();
            CloseableHttpResponse httpResponse = httpClient.execute(request);
                    
            System.out.println(httpResponse.getCode()); //200
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity)); //Success
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
Seagirt answered 20/1, 2022 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.