![](/img/trans.png)
[英]How to send json Object in http post request in Java
[英]How to post a complex JSON object to cURL request in java
我想将 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
我是新手,有人可以帮我吗?
您似乎发布了不正确的 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
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.