3

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
}

Nimantha
  • 6,405
  • 6
  • 28
  • 69
MelcomX
  • 41
  • 6
  • What happens to/where is the initialisation of `cred`? – xerx593 Feb 25 '21 at 21:16
  • @xerx593 Forgotten to copy that. It is now added. (`cred = new BasicAuthentificationProvider();` – MelcomX Feb 26 '21 at 08:51
  • ..(you can edit your post), please "sort" you code (&post), what you are trying to achieve is really simple* (curl -u...), and [that](https://github.com/apache/httpcomponents-client/blob/5.0.x/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientAuthentication.java) *is* the way to go... – xerx593 Feb 26 '21 at 13:40

0 Answers0