存储
  • 帮助与文档 存储

    示例功能

    • 上传Token生成
    • 文件信息提交

    使用上传SDK时,请先配置好服务端生成上传Token地址


    服务端生成上传Token代码如下:

    Java示例代码

    
    
    
    //生成上传视频凭证示例代码
    
    private static final String ACCESS_KEY = "替换为您的Access Key";
    private static final String SECRET_KEY = "替换为您的Secret Key";
    private static final String URL = "http://svc.suning.com/svc/api3/channel";
    
    private static final String ENCODE = "UTF-8";
    
    /**
     * 上传插件tokenUrl 实现
     * @return
     */
    public void getUpTokenController(HttpServletRequest request, HttpServletResponse response) {
        //所有接收参数都在上传插件中自动产生,请保持一下获取参数代码
        String name = request.getParameter("name");
        String summary = request.getParameter("summary");
        String cover_img = request.getParameter("cover_img");
        String length = request.getParameter("length");
        String ppfeature = request.getParameter("ppfeature");
    
        if (name == null) name = "";
        if (summary == null) summary = "";
        if (cover_img == null) cover_img = "";
        if (length == null) length = "0";
        if (ppfeature == null) ppfeature = "";
    
        String result = addVod(name, summary,
            length, cover_img, ppfeature);
    
        response.setContentType("application/json;charset=utf-8");
        response.getOutputStream().write(result.getBytes("UTF-8"));
        response.getOutputStream().flush();
    }
    
    /**
     * 创建视频并获取上传凭证uptoken
     *
     * @param name        视频名称,
     * @param summary     视频简介,可为空
     * @param length      视频文件大小,单位Byte
     * @param coverImgUrl 封面图地址,可为空
     * @param ppfeature   文件特征值
     * @return 视频信息
     */
    public static String addVod(String name, String summary,
            long length, String coverImgUrl, String ppfeature) {
    
        // 获取token认证字符串
        String auth = getAuthStr(ACCESS_KEY, SECRET_KEY);
    
        //中文字符处理
        name = encode(name);
        summary = encode(summary);
    
        String jsonTmpl = "{"
                + "\"ppfeature\": \"%s\","
                + "\"name\": \"%s\","
                + "\"summary\": \"%s\","
                + "\"coverimg\": \"%s\","
                + "\"length\": %s,"
                + "\"type\": 1"
                + "}";
        String body = String.format(jsonTmpl,  ppfeature,
                name, summary, coverImgUrl, length);
    
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", auth);
        headers.put("version", "3.0");
    
        //注:postJson方法发送POST请求时"Content-Type设置为application/json"
        String result = postJson(URL + "?getuptk=1", body, headers);
        return result;
    }
    
    
    //生成接口认证结果示例代码
    
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String ALGORITHM = "HmacSHA1";
    
    /**
     * 生成接口认证字符串
     */
    public static String getAuthStr(String accessKey, String secretKey) {
        if (accessKey == null || accessKey.equals("") || secretKey == null || secretKey.equals("")) {
            throw new IllegalArgumentException("empty accessKey or secretKey");
        }
    
        // 1. 生成签名信息:{"rid":"random-string", "deadline":deadline-second}
        String rid = UUID.randomUUID().toString();
        long deadline = System.currentTimeMillis()/1000 + 3600;
        String info = String.format("{\"rid\":\"%s\", \"deadline\":%s}", rid, deadline);
    
        // 2. 对签名信息做URL安全的Base64编码
        String encodedJsonBase64;
        try {
            encodedJsonBase64 = new String(Base64.encodeBase64(info.getBytes(DEFAULT_CHARSET), false, true));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(String.format("system not support encoding %s", DEFAULT_CHARSET));
        }
    
        // 3. 使用secret key 对签名信息加密
        byte[] sign;
        try {
            SecretKey sk = new SecretKeySpec(secretKey.getBytes(DEFAULT_CHARSET), ALGORITHM);
            Mac mac = Mac.getInstance(sk.getAlgorithm());
            mac.init(sk);
            sign = mac.doFinal(encodedJsonBase64.getBytes(DEFAULT_CHARSET));
        } catch (Exception e) {
            throw new RuntimeException("sha1 sign error");
        }
    
        // 4. 加密后的签名信息做URL安全的Base64编码
        String encoded_sign = new String(Base64.encodeBase64(sign, false, true));
    
        // 5. 生成最终认证字符串
        String accessToken = String.format("%s:%s:%s", accessKey, encoded_sign, encodedJsonBase64);
    
        return accessToken;
    }
    
    /**
     * 对中文UTF-8编码
     **/
    private static String encode(String str) {
        try {
            return URLEncoder.encode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            return str;
        }
    }
    
    
    /**
     * post方式提交json格式数据
     **/
    public static String postJson(String url, String body, Map<String, String> headers) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            for(String key : headers.keySet()){
                conn.setRequestProperty(key, headers.get(key));
            }
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(10 * 1000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());  //post 参数
            out.print(body);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException ex) {//ignore
            }
        }
        return result;
    }
                                        

    PHP核心代码

                                            
    <?php
    /**
     * 无插件上传,第三方获取upToken和视频fid的demo示例
     * post传参:
     * ppfeature:js计算出来的文件特征sha1值
     * category_id:分类id
     * name:视频名
     * summary:视频简介
     * length:视频大小,单位字节
     * cover_img:封面图url地址
     *
     */
    
    define('ACCESS_KEY', '替换为您的Access Key');
    define('SECRET_KEY', '替换为您的Secret Key');
    
    header('Access-Control-Allow-Origin:*');
    header('Access-Control-Allow-Credentials:true');
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
    header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
    
    //所有参数都是jssdk产生,php只需要接受就好
    $_POST['ppfeature'] = isset($_POST['ppfeature']) ? $_POST['ppfeature'] : '25600_' . sha1('1');
    $_POST['name'] = isset($_POST['name']) ? $_POST['name'] : 'test';
    $_POST['category_id'] = isset($_POST['category_id']) ? $_POST['category_id'] : '';
    $_POST['summary'] = isset($_POST['summary']) ? $_POST['summary'] : '';
    $_POST['cover_img'] = isset($_POST['cover_img']) ? $_POST['cover_img'] : '';
    $_POST['length'] = isset($_POST['length']) ? $_POST['length'] : 25600;
    
    function send_json_post($url, $json, $Authorization)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 75);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($json),
            "Authorization: $Authorization",
            'version: 3.0'
        ));
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
    function safe_base64encode($string)
    {
        $data = base64_encode($string);
        $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
        return $data;
    }
    
    function get_access_token($accessKey, $secretKey)
    {
        $json = json_encode(array(
            'rid' => md5(uniqid(mt_rand(), true)),
            'deadline' => time() + 86400 * 2,
        ));
        $encode_json = safe_base64encode($json);
        $sign = hash_hmac('sha1', $encode_json, $secretKey, true);
        $encode_sign = safe_base64encode($sign);
        $access_token = "{$accessKey}:{$encode_sign}:{$encode_json}";
        return $access_token;
    }
    
    //创建节目fid
    $url = 'http://svc.suning.com/svc/api3/channel?getuptk=1';
    $paramArr = array(
        'category_id' => $_POST['category_id'],
        'name' => $_POST['name'],
        'summary' => $_POST['summary'],
        'type' => 1,
        'cover_img' => $_POST['cover_img'],
        'length' => $_POST['length'],
        'ppfeature' => $_POST['ppfeature'],
    );
    $access_token = get_access_token(ACCESS_KEY, SECRET_KEY);
    $result = json_decode(send_json_post($url, json_encode($paramArr), $access_token), 1);
    if (isset($result['data'])) {
        $result['data']['upToken'] = $result['data']['up_token'];
        $result['data']['fId'] = $result['data']['fid'];
    }
    echo json_encode($result);
                                            
                                        
    • 文本导读:
    • 示例功能
    • Java示例代码
    • PHP核心代码
苏宁视频云服务