pinnaclesports api basic auth with java

时间:2014-12-20 18:17:29

标签: java api

当尝试使用api帐户余额时,我有一个例外:

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

以下是代码:

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();

}

2 个答案:

答案 0 :(得分:0)

我认为您的身份验证已损坏或未正确设置。 API使用 Basic Auth 和Base64编码的用户名/密码对。您应该阅读http://www.pinnaclesports.com/en/api/manual#authentication并确保您的授权正确无误。

以下是对HTTP状态代码401的解释:

  

类似于403 Forbidden,但专门用于身份验证时使用   有可能但已经失败或尚未提供。响应   必须包含一个包含挑战的WWW-Authenticate头字段   适用于所请求的资源。

答案 1 :(得分:0)

尝试使用Authenticator,如下所示:

    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()));

如果这不起作用,请尝试使用HttpURLConnection代替URLConnection, 像这样:

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

您可能还会使用Apache Commons找到this related post helpful