您好我尝试使用toggl API将报告作为csv文件获取。但是我似乎无法弄清楚如何使用所有参数正确地获取请求。我找到了一个很棒的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);
[...]
答案 0 :(得分:0)
根据他们的API文档:
您只能使用API令牌在报告API中进行身份验证。对于HTTP Basic Auth,您必须在请求中添加Authorization标头。令牌以用户名的形式发送,字符串'api_token'作为密码发送。请尽可能使用http库提供的工具和界面进行Basic Auth(例如,curl使用-u开关)。
和这个SO answer你应该做这样的事情进行身份验证
String encoded = Base64.encode(api_token + ":api_token");
connection.setRequestProperty("Authorization", "Basic "+encoded);