Edit: I have already tried the solutions provided in the comments and they don't work. Adding raw headers works, but I am trying to avoid doing that.
I am facing a bizarre situation. I have a resource protected by basic auth which I am able to query easily via browser, Postman and curl. But in Java, I am not able to query it and getting a 403 forbidden error. I followed the below example:
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "password");
provider.setCredentials(AuthScope.ANY, credentials);
CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpResponse response = client.execute(new HttpGet("https://hostname.com/api/detail?query=xx"));
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode); // prints 403 forbidden
When I inspected the objects in debugger, I noticed HttpGet object's headers were empty. That is, it wasn't passing the "Authorization" header with a "Basic asdflkhjWskjhakljhasdfkasdflkjh=" value.
So I manually added the header with the correct value and it worked (status 200 OK).
Can someone please help me figure out why this is happening and how can I use the HttpClient API to set the right headers instead of adding the header manually?
This is my dependency:
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>