Mythul
Mythul

Reputation: 1807

Correct Basic Authentication in HttpClient 4.3.x

I currently use the following basic authentication implementation:

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(uri);

        // Set the basic authentication
        httpGet.addHeader(BasicScheme.authenticate(
                new UsernamePasswordCredentials("user", "pass"),
                "UTF-8", false));

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        ...

The code works fine however BasicScheme.authenticate is deprecated.

What is the correct way to implement the basic authentication for a request in HttpClient 4.3.x?

Upvotes: 0

Views: 263

Answers (1)

spock8190
spock8190

Reputation: 81

The following works for me -

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet httpGet = new HttpGet(uri);

    // Set the basic authentication
    String encoding = Base64Encoder.encode("user:pass");
    httpGet.setHeader("Authorization", "Basic" + encoding);

    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity entity = httpResponse.getEntity();

Please let me know if it works fine for you.

Upvotes: 1

Related Questions