I'm trying to perform a REST API get request using org.apache.http.client.HttpClient on 4.3.6 version, but receiving a 401 error. I am using Basic Authentication
Here is my example code
BasicCredentialsProvider credprov = new BasicCredentialsProvider();
credprov.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(API_USERNAME, API_PASSWORD));
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCredentialsProvider(credprov);
HttpClient client = builder.build();
HttpGet httpget = new HttpGet(API_TEST_URI);
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());
}
if (entity != null) {
entity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
This is returning a 401, even though all the details are correct. I was debugging through the HttpClient code, and found the original response is returning a 401 with the WWW-Authenticate header is just set as "Basic" with nothing else. This then ends up with a MalformedChallengeException "Authentication challenge is empty" exception.
I have tried changed the code a bit to directly set the header on the httpget variable with the basic authentication
httpget.addHeader("Authorization", "Basic " + Base64Encoder.encode ("username:password"));
and this has worked (showing that the authentication details are correct.
Can anyone find any problems with this approach and why it doesnt work?