主要记录一下接入抖音开放平台遇到问题较多的部分(上传视频+创建视频),其他的接口可下载开放平台提供的api引入项目调用即可。
视频推广到抖音的整个流程:授权认证(app SDK获取授权码code =》 服务端获取accessToken、获取用户信息) =》 发布视频(上传视频+创建视频)。
视频发布后可调用查询视频接口(视频管理-》查询视频=》查询视频列表)获取视频相关数据(审核状态、统计数据),每个用户的全部视频合计的数据明细(今日/7日/30日)可通过编写job自行统计(开放平台也提供了单个视频的统计数据接口)。
考虑一个用户绑定多个抖音账户问题,记录信息时建议同时登记系统userId、抖音视频itemId、抖音openId。
1、上传视频
/**
*上传视频,获取video_id
*/
public void uploadVideo(String openId,String accessToken){
VideoCreateAwemeCreateInlineResponse200 result;
try {
String url = "https://open.douyin.com/video/upload/?open_id=" + openId + "&access_token="+ accessToken;
HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//videoFlie为byte[]类型
builder.addBinaryBody("video", videoFlie, ContentType.MULTIPART_FORM_DATA,
"xxx.mp4");
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
String resData = EntityUtils.toString(response.getEntity());
result = JSON.parseObject(resData, VideoCreateAwemeCreateInlineResponse200.class);
} catch (Exception e) {
//TODO 报错/日志处理
}
VideoCreateAwemeCreateInlineResponse200Data data = result.getData();
Integer resCode = data.getErrorCode();
//refreshToken无效,重新授权
if (10010 == resCode
|| 10008 == resCode) {
//TODO 抛错->重新授权
//accesstoken无效,刷新access_token重试
} else if (2190002 == resCode
|| 10010 == resCode) {
//刷新token
refreshToken();
//重新上传
uploadVideo(openId,accessToken);
return;
} else if (0 != data.getErrorCode()) {
//TODO
}
//创建视频
createVideo(data.getVideo().getVideoId(),openId,accessToken);
}
2、创建视频
/**
* 创建视频
*@param videoId 创建视频接口获取的videoId
*/
public void createVideo(String videoId,String openId,String accessToken){
VideoCreateAwemeCreateInlineResponse2001 result;
try {
String url ="https://open.douyin.com/video/create/?open_id=" + openId + "&access_token="
+ accessToken;
Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("video_id", videoId);
paramMap.put("text", "视频标题");
String paramJson = JSON.toJSONString(paramMap);
//post方法自行选择,这边可多设置些超时时间
String resStr = HttpUtil.sendPost(url, paramJson, ContentTypeEnum.JSON, CharSetEnum.UTF8, 90000);
result = JSON.parseObject(resStr, VideoCreateAwemeCreateInlineResponse2001.class);
} catch (ApiException e) {
//TODO
}
VideoCreateAwemeCreateInlineResponse2001Data data = result.getData();
Integer resCode = data.getErrorCode();
//refreshToken无效,重新授权
if (10010 == resCode
|| 10008 == resCode) {
//TODO 抛错->重新授权
//accesstoken无效,刷新access_token重试
} else if (2190002 == resCode
|| 10010 == resCode) {
//刷新token
refreshToken();
//重新上传
createVideo(videoId);
return;
} else if (0 != data.getErrorCode()) {
//TODO
}
}