0

Hi I'm trying to use the toggl API to get reports as csv files. However I cannot seem to figure out how to make the get request right using all the parameters. I found a great Python script for it (https://baxeico.wordpress.com/2014/03/13/build-excel-timesheet-toggl-api-python/) but am unfortunately not able to translate it into Java. Help would be greatly appreciated. I seem to have a problem with the api_token. Since I always receive error 401 saying that the api_token is missing. Here the beginning of my code with adapted user details ;)

public class HttpURLConnectionExample {

private final String USER_AGENT = "Mozilla/5.0";
String workspaceId = "123456";
String apiToken = "qrstuvwxyz123456789";


public static void main(String[] args) throws Exception {

    HttpURLConnectionExample http = new HttpURLConnectionExample();

    System.out.println("Testing 1 - Send Http GET request");
    http.sendGet();

}

// HTTP GET request
private void sendGet() throws Exception {

    String url = "https://www.toggl.com/reports/api/v2/summary?user_agent='username'";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    //con.setRequestProperty("User-Agent", userAgent);

    // that's where I'd like to add the workspace ID and my API token
    con.setRequestProperty("api_token", apiToken);
    con.setRequestProperty("workspace_id", workspaceId);


    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

[...]

oddpodm
  • 157
  • 2
  • 6

1 Answers1

0

According to their API-documentation:

You can authenticate in the reports API only with your API token. For HTTP Basic Auth you have to add the Authorization header with the request. The token is sent as user name and the string 'api_token' as the password. Whenever possible please use the tools and interfaces provided by your http library to do Basic Auth (for example, curl uses the -u switch for that).

and this SO answer you should do something like this for authentication

String encoded = Base64.encode(api_token + ":api_token");
connection.setRequestProperty("Authorization", "Basic "+encoded);
Community
  • 1
  • 1
Frank
  • 2,036
  • 1
  • 20
  • 32