Java httpClient: Authentification Get does not work

Viewed 102

I'm writing an API-interpreter in Java using the Apache-HttpClient(Version 4.5.13) . The client has to authenticate itself using the http basic authentification. (I think it's worth mentioning, that I use HTTPS, and that the URL is correct.) The implementation follows a tutorial linked in the source. Furthermore I considered this example by the apache-team.

The problem is, that I get an unauthorized error. To test the webserver I've used curl with the following thing: curl https://example.com/path/to/protected/thing -u clientkey:clientsecret The result is the expected huge json.

I've implemented the following version:

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.*;
import org.apache.http.*;
import org.apache.http.util.EntityUtils;

public ArrayList<JsonObject> getJson(String what){

            CredentialsProvider cred; //Direct use of https://www.tutorialspoint.com/apache_httpclient/apache_httpclient_user_authentication.htm

            HttpClientBuilder clientbuilder = HttpClients.custom();
            CloseableHttpClient httpClient;
            cred.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(ClientKey, ClientSecret)); //I've tried to exchange Clientkey and ClientSecret but that does not change anything. 
            cred = new BasicCredentialsProvider();
            clientbuilder = clientbuilder.setDefaultCredentialsProvider(cred);
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(cred).build();
            request = new HttpGet(String.valueOf(APIURL) + what);
            HttpResponse response = httpClient.execute(request);

            String responsejson = EntityUtils.toString(response.getEntity()); // https://stackoverflow.com/a/39978542/6704070
            System.out.println(responsejson); // Prints the 401 message
}

0 Answers
Related