0

I am trying to make a get request on an API, that has basic authentication, but even though I have the correct username and password, it won't work.

When I'm trying to reach the API with curl (Linux command) it works fine.

curl -u "user:password" -s https://dummy/link/1

Do I need to specify that the response must be enter code hereJSON?

I am using Maven: org.apache.httpcomponents:httpclient:4.5.13 dependency

CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user","password");
provider.setCredentials(AuthScope.ANY, credentials);

HttpClient client = HttpClientBuilder.create()
    .setDefaultCredentialsProvider(provider)
    .build();

HttpResponse response = client.execute(
    new HttpGet("https://dummy/link/1");
int statusCode = response.getStatusLine()
    .getStatusCode();

if(statusCode != HttpStatus.SC_OK){
  System.out.println(statusCode);
}else{
  System.out.println(response);
}
radurbalau
  • 99
  • 1
  • 9

1 Answers1

0

I stumbled on the same issue. I noticed my request with curl had the header

Authorization: Basic base64(username:password)

that my get request was missing, then i found this answer that solved the problem but with a deprecate use of BasicScheme.authenticate and finally removed the deprecated part using this other answer:

httpget.setHeader( new BasicScheme(StandardCharsets.UTF_8).authenticate(credentials , httpget, null) );

Now it works. Did not check the long way as specified in the first answer.

Sergio
  • 89
  • 1
  • 6