我正在尝试使用 Scribe 使用他们的 V3 API(使用 Java,在 Google App Engine 中)将 GPX 文件(未压缩)上传到 Strava:
String url = "https://www.strava.com/api/v3/uploads?access_token=<TOKEN>";
OAuthRequest req = new OAuthRequest(Verb.POST, url);
req.addQuerystringParameter("private", "1");
req.addQuerystringParameter("activity_type", "bike");
req.addQuerystringParameter("data_type", "gpx");
req.addQuerystringParameter("external_id", <Unique String>);
req.addHeader("Content-Type", "multipart/form-data");
String gpx = <Content of GPX file to Upload>;
req.addBodyParameter("file", gpx);
Response response = request.send();
结果是我从 Strava 收到响应代码 500(内部错误),并且它没有上传 GPX Activity 。
我想这与我如何形成 HTTP 多部分 POST 有关,这是在 Strava 文档中定义的 here作为:
DEFINITION
POST https://www.strava.com/api/v3/uploads
EXAMPLE REQUEST
$ curl -X POST https://www.strava.com/api/v3/uploads \
-F access_token=83ebeabdec09f6670863766f792ead24d61fe3f9 \
-F activity_type=ride \
-F file=@test.fit \
-F data_type=fit
Parameters:
<OTHERS>
file: multipart/form-data required
the actual activity data, if gzipped the data_type must end with .gz
关于如何使这项工作有任何想法吗?谢谢。
编辑:通过我自己的进一步调查发现了几件事:
- Scribe 主要用于签署 oauth,因此作者并未专注于添加处理多部分/表单数据的功能(尽管人们建议添加此类内容)
- 我可以使用 Apache 类之一 (MultipartEntity) 和 Scribe 来做到这一点,但我认为 Google App Engine 不支持 Apache 库。参见 this线程,这将是完美的,除了 Apache/GAE 问题
最佳答案
这是一个完整的解决方案。传递您的不记名 token 和文件名以上传。这适用于 FIT 文件,但对于 GPX 来说只是一个简单的更改。取自这里:
https://github.com/davidzof/strava-oauth/
public static long uploadActivity(String bearer, String fileName) {
JSONObject jsonObj = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"https://www.strava.com/api/v3/uploads");
httpPost.addHeader("Authorization", "Bearer " + bearer);
httpPost.setHeader("enctype", "multipart/form-data");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
reqEntity.addPart("activity_type", new StringBody("ride"));
reqEntity.addPart("data_type", new StringBody("fit"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileBody bin = new FileBody(new File(fileName));
reqEntity.addPart("file", bin);
httpPost.setEntity(reqEntity);
HttpResponse response;
try {
response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
System.out.println(content);
JSONParser jsonParser = new JSONParser();
jsonObj = (JSONObject) jsonParser.parse(content);
}
} catch (ParseException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) jsonObj.get("id");
}
关于java - 使用 Scribe 上传 Strava V3 API(在 Google App Engine 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20370095/