我想将JSONObject发布到 https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate
使用HttpPost和我的JAVA代码
String AccessToken = "ya29.Glv7A7pTaXdXn8EIHlMnGDBMt34OB72bmKowLFxVM7w7MTu7PRqVoBq7eGd0ljMtOk5aDM6y9WkCDdgZ113rzSzXQe6CZV3UXuNvkzWesAl6CfJoA2IZ9U2C9BaG";
JSONObject jobj = new JSONObject();
JSONObject jobj3 = new JSONObject();
jobj3.put("durationMillis", 86400000);
JSONObject jobj2 = new JSONObject();
jobj2.put("dataTypeName", "com.google.step_count.delta");
jobj2.put("dataSourceId", "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps");
JSONArray jar = new JSONArray();
jar.add(jobj2);
jobj.put("aggregateBy", jar);
jobj.put("bucketByTime", jobj2);
jobj.put("startTimeMillis", 1487721600000L);
jobj.put("endTimeMillis", 1487772000000L);
System.out.println("jobj" + jobj.toJSONString());
String ApiUrl = "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate?access_token=" + AccessToken;
HttpClient httpclient = HttpClientBuilder.create().build();
try {
HttpPost httpPost = new HttpPost(ApiUrl);
httpPost.addHeader("Authorization", "Bearer " + AccessToken);
httpPost.setEntity(new StringEntity(jobj.toJSONString()));
//sets a request header so the page receving the request
//will know what to do with it
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpPost);
System.out.println("\nSending 'GET' request to URL : " + ApiUrl);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("line" + line);
}
} catch (Exception e) {
System.out.println("Exception at getDataFromUrl ,error is " + e.getMessage());
}
它给我的错误
{"error":{"errors":[{"domain":"global","reason":"invalidArgument","message":"Bad Request"}],"code":400,"message":"Bad Request"}}
提到https://developers.google.com/fit/scenarios/read-daily-step-total
我是新手,有人可以帮助我吗?
答案 0 :(得分:1)
看来你正在发布错误的JSON。 您的代码生成的JSON:
`
{
"endTimeMillis": 1487772000000,
"startTimeMillis": 1487721600000,
"bucketByTime": {
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps",
"dataTypeName": "com.google.step_count.delta"
},
"aggregateBy": [
{
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps",
"dataTypeName": "com.google.step_count.delta"
}
]
}
`
根据规范,bucketByTime
应为"bucketByTime": { "durationMillis": 86400000 }
您似乎根本没有将代码中的jobj3
变量添加到有效负载中,其中包含正确的bucketByTime
值。