EDIT: OK I found out that it is definitely an authentication issue: This short Python script does the thing just fine:
import requests
from requests.auth import HTTPBasicAuth
URL = "https://wiki.myCompany.corp/confluence-dev/rest/api/content/180158489";
r = requests.get(URL, auth = HTTPBasicAuth('myUser', 'myPass'), verify=False)
r.raise_for_status()
print(r.json())
Why doesn't it work with Java??
Initial question:
I'm trying to write a simple Http request using Apache httpclient/httpcore to get the content of a Confluence page, but all I get is status 404.
This is my code:
String url = "https://wiki.mycompany.corp/confluence-dev/rest/api/content/180158489";
HttpHost proxy = new HttpHost("proxy.myCompany.at", 57165);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("myUsername", "myPassword");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultCredentialsProvider(provider);
builder.setRoutePlanner(routePlanner);
HttpClient client = builder.build();
HttpGet get = new HttpGet(url);
HttpResponse r = client.execute(get);
System.out.println(r.getStatusLine().toString());
Output: HTTP/1.1 404 Not Found
When I open that URL in a browser I get the correct confluence JSON back, as long as I am logged in. When I log out and try to open that URL in a browser I get a JSON
{
"statusCode":404,
"data":
{
"authorized":false,
"valid":true,
"allowedInReadOnlyMode":true,
"errors":[],"successful":false
},
"message":"No content found with id: ContentId{id=180158489}",
"reason":"Not Found"
}
So to me this looks like that somehow the authentication from my code is not correctly working.
Do you have any ideas what could be wrong here?
Ok, I found the solution (somehow). In my Java code the authentication doesn't work (for whatever reasons, I've seen it done like that in multiple examples...).
Anyway, what is working though is if I set my header manually, like that:
HttpGet request = new HttpGet(url);
String authorizationString = "Basic " + Base64.getEncoder().encodeToString(("myUser:myPass").getBytes()).replace("\n", "");
request.setHeader(HttpHeaders.AUTHORIZATION, authorizationString);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().toString());
Result:
HTTP/1.1 200 OK