我正在尝试使用Scribe使用他们的V3 API(使用Java,在Google App Engine中)将一个GPX文件(不是gzip)上传到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活动。
我想这与我如何形成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
有关我如何才能使这项工作的任何想法,请?谢谢。
编辑:通过我自己的进一步调查发现了一些事情:答案 0 :(得分:1)
这是一个完整的解决方案。传递您的持票人令牌和文件名进行上传。这适用于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");
}
答案 1 :(得分:0)
最终我在Stack Overflow上找到了this solution,它提供了使用Apache类的方法
MultipartEntity
在Google App Engine的限制范围内。我只需要在我的GAE项目中添加三个Apache JAR:httpclient-4.3.1.jar,httpcore-4.3.jar和httpmime-4.3.1.jar。
然后我结合this解决方案,允许我添加
FileBody
到
MultipartEntity
(在我的情况下是GPX&#34;文件&#34;我用String构建)。这两种解决方案完美结合在一起!