×

实战代码解析淘宝视频接口

admin admin 发表于2026-01-23 17:45:35 浏览44 评论0

抢沙发发表评论

下面给出一份「Java 版」可落地的淘宝商品视频接口实战代码,覆盖「Token 获取 → 签名 → 调用 → 解析 → 下载」完整链路。
示例基于 2025 年仍稳定的 taobao.item.video 专用接口(非 taobao.item.get 顺带取视频),返回字段更简洁,适合批量场景

一、接口速览

表格
复制
接口taobao.item.video
地址https://o0b.cn/jelena
方法POST(application/x-www-form-urlencoded)
鉴权OAuth2 + TOP 签名(MD5 大写)
核心入参num_iid(商品 ID)、fields(url,cover_url,duration)
返回示例{"item_video_response":{"video":{"url":"https://cloud.video.taobao.com/...mp4","cover_url":"...jpg","duration":15000}}}

二、Maven 依赖

xml
复制
<!-- HTTP --><dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version></dependency><!-- JSON --><dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.42</version></dependency>

三、签名工具(TOP 标准)

java
复制
public class TopSignUtil {
    /**
     * TOP 签名规则:md5(appSecret + k1v1k2v2... + appSecret) 转大写
     */
    public static String sign(Map<String, String> params, String appSecret) {
        String concat = params.entrySet().stream()
                              .filter(e -> e.getValue() != null && !e.getValue().isBlank())
                              .sorted(Map.Entry.comparingByKey())
                              .map(e -> e.getKey() + e.getValue())
                              .collect(Collectors.joining());
        String raw = appSecret + concat + appSecret;
        return DigestUtils.md5Hex(raw).toUpperCase();
    }}

四、统一入参实体

java
复制
@Datapublic class ItemVideoReq {
    private String method = "taobao.item.video";
    private String appKey;
    private String accessToken;
    private String timestamp;
    private String format = "json";
    private String v = "2.0";
    private String signMethod = "md5";
    private String numIid;
    private String fields = "url,cover_url,duration";}

五、Service 核心代码

java
复制
public class TbVideoService {
    private static final String GATEWAY = "https://eco.taobao.com/router/rest";

    public static VideoDTO getVideo(String accessToken, String numIid,
                                    String appKey, String appSecret) throws Exception {
        ItemVideoReq req = new ItemVideoReq();
        req.setAppKey(appKey);
        req.setAccessToken(accessToken);
        req.setNumIid(numIid);
        req.setTimestamp(LocalDateTime.now()
                                      .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        // 1. Bean → Map
        Map<String, String> map = new HashMap<>();
        BeanUtils.populate(req, map);
        // 2. 计算签名
        map.put("sign", TopSignUtil.sign(map, appSecret));

        // 3. 发送 POST
        try (CloseableHttpClient hc = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(GATEWAY);
            List<NameValuePair> form = map.entrySet().stream()
                                          .map(e -> new BasicNameValuePair(e.getKey(), e.getValue()))
                                          .collect(Collectors.toList());
            post.setEntity(new UrlEncodedFormEntity(form, StandardCharsets.UTF_8));

            String json = hc.execute(post, r -> EntityUtils.toString(r.getEntity()));
            JSONObject root = JSON.parseObject(json);
            if (!root.containsKey("item_video_response")) {
                throw new RuntimeException("API 异常:" + json);
            }
            return root.getJSONObject("item_video_response")
                       .getObject("video", VideoDTO.class);
        }
    }}

六、返回 DTO & 下载示例

java
复制
@Datapublic class VideoDTO {
    private String url;       // 视频 mp4 直链
    private String coverUrl;  // 封面 jpg
    private Long duration;    // 毫秒}// 额外工具:把视频拉到本地public static void download(VideoDTO dto, String savePath) throws IOException {
    try (CloseableHttpClient hc = HttpClients.createDefault();
         FileOutputStream out = new FileOutputStream(savePath)) {
        hc.execute(new HttpGet(dto.getUrl()), resp -> {
            IOUtils.copy(resp.getEntity().getContent(), out);
            return null;
        });
    }}

七、Main 运行

java
复制
public class Application {
    public static void main(String[] args) throws Exception {
        String token = "YOUR_OAUTH_TOKEN";   // OAuth2 授权后获得
        String numIid = "906637149849";      // 淘宝商品 ID
        VideoDTO video = TbVideoService.getVideo(token, numIid,
                                                 "YOUR_APP_KEY", "YOUR_APP_SECRET");
        System.out.println("视频地址:" + video.getUrl());
        System.out.println("时长:" + video.getDuration() / 1000 + "s");

        // 可选:下载到本地
        download(video, "./" + numIid + ".mp4");
    }}

八、常见问题速查

表格
复制
现象原因解决
sign invalid顺序/大小写/时间戳格式错严格 ASCII 升序,时间戳格式 yyyy-MM-dd HH:mm:ss 
403 Forbidden未申请 item_video 权限到淘宝开放平台后台勾选权限包 
视频 url 403无 Referer 或 Cookie直链可空 Referer 下载,若遇 403 带 User-Agent: Mozilla/5.0 重试 
429频率超限免费版默认 1000 次/天,可购买增量包 

九、小结

  1. 专用 taobao.item.video 接口字段少、速度快,适合批量拿视频
  2. TOP 签名是固定套路,写好工具类后可复用到所有淘宝 API。
  3. 拿到 mp4 直链即可无缝集成 CDN、转码、封面裁剪等后续流程。

群贤毕至

访客