-1

When trying to get account balance used api I got an exception:

IOException: Server returned HTTP response code: 401 for URL: 
https://api.pinnaclesports.com/v1/client/balance

Here's the code:

public void getBalance() throws Exception{

    byte[] bytes = "username:password".getBytes("UTF-8");
    String encoded = Base64.encodeBase64String(bytes);
    System.out.println(encoded);
    URL api = new URL("https://api.pinnaclesports.com/v1/client/balance");
    URLConnection apiConnection = api.openConnection();
    apiConnection.addRequestProperty("Authorization", "Basic "+encoded);

    BufferedReader in = new BufferedReader(new InputStreamReader(apiConnection.getInputStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();

}
janos
  • 120,954
  • 29
  • 226
  • 236
user3911971
  • 131
  • 1
  • 9

2 Answers2

0

I think your authentication is broken or not set properly. The API uses Basic Auth and a Base64 encoded username/password pair. You should read http://www.pinnaclesports.com/en/api/manual#authentication and make sure that your authorization is correct.

Here's an explanation for HTTP status code 401:

Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.

cringe
  • 13,401
  • 15
  • 69
  • 102
0

Try using an Authenticator, like this:

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "password".toCharArray());
        }
    });
    URL api = new URL("https://api.pinnaclesports.com/v1/client/balance");
    BufferedReader in = new BufferedReader(new InputStreamReader(api.openStream()));

Or if that doesn't work, then try using an HttpURLConnection instead of URLConnection, like this:

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty  ("Authorization", "Basic " + encoded);

You might also find this related post helpful, using Apache Commons.

Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236