【问题标题】:How to make a get request to toggl API using java?如何使用java向toggl API发出get请求?
【发布时间】:2016-05-22 03:30:30
【问题描述】:

您好,我正在尝试使用 toggl API 将报告作为 csv 文件获取。但是,我似乎无法弄清楚如何使用所有参数正确地发出 get 请求。我为它找到了一个很棒的 Python 脚本 (https://baxeico.wordpress.com/2014/03/13/build-excel-timesheet-toggl-api-python/),但不幸的是我无法将它翻译成 Java。帮助将不胜感激。 我似乎对 api_token 有问题。因为我总是收到错误 401 说缺少 api_token。 这是我的代码的开头,其中包含经过调整的用户详细信息;)

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

[...]

【问题讨论】:

    标签: java get-request


    【解决方案1】:

    根据他们的 API 文档:

    您只能使用您的 API 令牌在报告 API 中进行身份验证。对于 HTTP Basic Auth,您必须在请求中添加 Authorization 标头。令牌作为用户名发送,字符串“api_token”作为密码发送。请尽可能使用您的 http 库提供的工具和接口进行基本身份验证(例如,curl 使用 -u 开关)。

    这个SO answer你应该做这样的事情来进行身份验证

    String encoded = Base64.encode(api_token + ":api_token");
    connection.setRequestProperty("Authorization", "Basic "+encoded);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2017-06-02
      • 2012-06-14
      • 2014-09-30
      相关资源
      最近更新 更多