优酷接口的使用

1、定义上传视频的jsp <%@ page language="java" import="java.util.*" pageEncoding="utf-8" isELIgnored="false"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>" /> <meta charset="utf-8"> <title>达内·求职秀--求职秀-视频上传</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <link href="http://open.youku.com/assets/lib/bootstrap2.1.0/css/bootstrap.css" rel="stylesheet"> <link href="http://open.youku.com/assets/lib/bootstrap2.1.0/css/bootstrap-responsive.css" rel="stylesheet"> <style> .uploadfile{width:150px;height: 14px;vertical-align: top;} </style> <script src="http://open.youku.com/assets/lib/jquery-1.8.1.min.js"></script> <script src="http://open.youku.com/assets/lib/uploadjs.php"></script> <script> var USE_STREAM_UPLOAD = true; jQuery(document).ready(function(){ //newWindow新弹出窗口方式 var param = {client_id:"3f55944758a967be", access_token:"feb81d9c7eff2b440d302770a4f389d5", oauth_opentype:"newWindow", oauth_redirect_uri:"<%=basePath%>user/jobSoo/oauth_result_newwindow.html", oauth_state:"", completeCallback:"uploadComplete", categoryCallback:"categoryLoaded"}; //判断视频格式 $("#fileInput").live('change',function(){ var fileName =  $(this).val(); //wmv,avi,dat,asf,rm,rmvb,ram,mpg,mpeg,3gp,mov,mp4,m4v,dvix,dv,dat,mkv,flv,vob,qt,divx,cpk,fli,flc,mod if( !fileName.match(/.wmv|.avi|.dat|.asf|.rm|.rmvb|.ram|.mpg|.mpeg|.3gp|.mov|.mp4|.m4v|.dvix|.dv|.dat|.mkv|.flv|.vob|.qt|.divx|.cpk|.fli|.flc|.mod/i)){ alert("视频格式格式或大小无效,最大支持上传1 GB, 视频文件允许上传的视频格式为:wmv,avi,dat,asf,rm,rmvb,ram,mpg,mpeg,3gp,mov,mp4,m4v,dvix,dv,dat,mkv,flv,vob,ram,qt,divx,cpk,fli,flc,mod。"); //中断不了视频的提交事件 // return; $(this).val(""); $("#input01").val(""); $("#input02").val(""); $("#textarea").val(""); } checkDric(); checkTitle(); checkTags(); }); youkuUploadInit(param); //将信息清空 $("#textarea").val(""); $("#input01").val(""); $("#input02").val(""); //重写取消上传的按钮的事件 var obj = $("#btn-upload-stop"); obj.removeAttr("live"); obj.live('click',function (){ //$(this) //就是点击那那个button return; }); var obj2 = $("#btn-upload-start"); obj2.removeAttr("live"); obj2.live('click',function (){ checkTitle(); checkTags(); checkDric(); }); }); //上传完成时回调方法 function uploadComplete(data){ var url =window.location.href; url = url.substring(url.indexOf("=")+1); window.location.href="<%=basePath%>jobSoo/uploadVideo?videoId=" + data.videoid+"&videoTitle="+data.title+"&jobSooId="+url ; } //分类加载后回调方法 function categoryLoaded(data){ if(data.categories) { var tpl = ''; for (var i=0; i<data.categories.length; i++) { if(data.categories[i].term == 'Ads'){ tpl += '<option value="' + data.categories[i].term + '" selected>' + data.categories[i].label + '</option>'; }else{ tpl += '<option value="' + data.categories[i].term + '" >' + data.categories[i].label + '</option>'; } } $("#category-node").html(tpl); } } /** *检测标题 */ function checkTitle(){ //显示数据 $("#title_error_span").hide(); $("#title_right_span").hide(); //获取昵称 var title = $("#input01").val(); //判断用户名是否为空 if(title == "" || title == null){ $("#title_right_span").hide(); $("#title_error_span").show(); }else if(title.length>30){ $("#title_error_text").text("标题最多能输入30个字"); $("#title_right_span").hide(); $("#title_error_span").show(); }else{ $("#title_error_span").hide(); $("#title_right_span").show(); } } /** *检测标签 */ function checkTags(){ //显示数据 $("#tags_error_span").hide(); $("#tags_right_span").hide(); var tags = $("#input02").val(); //判断用户名是否为空 if(tags == "" || tags == null){ $("#tags_right_span").hide(); $("#tags_error_span").show(); }else if(tags.length < 2){ $("#tags_right_span").hide(); $("#tags_error_span").show(); $("#tags_error_text").text("标签不能少于两个字符"); }else{ $("#tags_error_span").hide(); $("#tags_right_span").show(); } } /** * 检查简介 */ function checkDric(){ //显示数据 $("#description_error_span").hide(); $("#description_right_span").hide(); var content = $("#textarea").val().toString(); var len = 0; if (content != null && content != "") { for ( var j = 0; j < content.length; j++) { var str = content.charAt(j); var reg = /^[\u4E00-\u9FA5]+$/; if (reg.test(str)) { len += 2; } else { len += 1; } } } if(content == "" || len == 0 ){ $("#description_right_span").hide(); $("#description_error_text").text("请输入简介"); $("#description_error_span").show(); $("#btn-upload-start").attr("disabled","disabled"); } if(len <= 25 && len >0){ $("#description_error_span").hide(); $("#description_right_span").show(); $("#btn-upload-start").attr("disabled",false); }else{ $("#description_right_span").hide(); $("#description_error_span").show(); $("#btn-upload-start").attr("disabled","disabled"); } } </script> </head> <body onload="getJobSooId();"> <!-- 头部 --> <jsp:include page="../../public/header.jsp"></jsp:include> <div id="youku-upload"> <div class="container"> <form  class="well form-horizontal"  name="video-upload"> <fieldset><div class="control-group"> <label class="control-label" for="spanSWFUploadButton">选择文件:</label> <div id="uploadControl" class="controls"> </div> </div> <div class="control-group"> <label class="control-label" for="input01">标题:</label> <div class="controls"> <input type="text" class="input-xlarge" id="input01" name="title" onblur="checkTitle()"> <span id="title_error_span" style="display:none"> <img src="images/error02.gif" width="17" height="17" alt="" /> &nbsp;<span id="title_error_text">请输入标题</span> </span> <span id="title_right_span" style="display:none"> <img src="images/right.gif" width="17" height="17" alt=""/> &nbsp;<span>标题可用</span> </span> </div> </div> <div class="control-group"> <label class="control-label" for="textarea">简介:</label> <div class="controls"> <textarea class="input-xlarge" id="textarea" rows="3" name="description" onkeyup="checkDric()"></textarea> <span id="description_error_span" style="display:none"> <img src="images/error02.gif" width="17" height="17" alt="" /> &nbsp;<span id="description_error_text">简介过长</span> </span> <span id="description_right_span" style="display:none"> <img src="images/right.gif" width="17" height="17" alt=""/> &nbsp;<span>简介可用</span> </span> </div> </div> <div class="control-group"> <label class="control-label" for="input02">标签:</label> <div class="controls"> <input type="text" class="input-xlarge" id="input02" name="tags" onblur="checkTags()"> <span class="help-inline"></span> <span id="tags_error_span" style="display:none"> <img src="images/error02.gif" width="17" height="17" alt="" /> &nbsp;<span id="tags_error_text">请输入标签</span> </span> <span id="tags_right_span" style="display:none"> <img src="images/right.gif" width="17" height="17" alt=""/> &nbsp;<span>标签可用</span> </span> </div> </div> <div class="control-group"> <label class="control-label" for="category-node">类别:</label> <div class="controls"> <select id="category-node" name="category" ></select> </div> </div> <div class="control-group"> <label class="control-label">版权所有</label> <div class="controls"> <label class="radio inline"> <input type="radio" name="copyright_type" id="copyright_type2" value="original" checked="">原创</label> <label class="radio inline"><input type="radio" name="copyright_type" id="copyright_type1" value="reproduced">转载</label> </div> </div> <div class="control-group"> <label class="control-label">视频权限</label> <div class="controls"> <label class="radio inline"> <input type="radio" name="public_type" id="public_type1" value="all" checked="">公开 </label> <label class="radio inline"> <input type="radio" name="public_type" id="public_type2" value="friend">仅好友 </label> <label class="radio inline"> <input type="radio" name="public_type" id="public_type3" value="password">输入密码观看 </label> <label class="radio inline" style="display:none" id="passwrod"> <input type="text" class="input "name="watch_password"> </label> </div> </div> <div class="form-actions"> <button type="button" class="btn btn-primary start"  id="btn-upload-start" > <i class="icon-upload icon-white"></i> <span>开始上传</span> </button> </div> </fieldset> </form> <div class="row" > <div class="span5" id="upload-status-wraper" ></div> </div> <div class="well"><h3>说明</h3><ul><li>最大支持上传<strong>1 GB</strong> 视频文件</li><li> 允许上传的视频格式为:wmv,avi,dat,asf,rm,rmvb,ram,mpg,mpeg,3gp,mov,mp4,m4v,dvix,dv,dat, </br> mkv,flv,vob,ram,qt,divx,cpk,fli,flc,mod。不符合格式的视频将会被丢弃,请确保视频格式的正确性,避免上传失败 </li></ul> </div> </div> <div id="complete"></div> <div id="login" style="width:100%;height:100%;position:fixed;z-index:999;left:0px;top:0px;overflow:hidden;display:none;"> </div> <!-- 尾部 --> <jsp:include page="../../public/footer.jsp"></jsp:include> <style> .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container{ width:1040px; margin:0 auto;} .form-horizontal{ padding-left:100px; margin:0 auto 20px; overflow:hidden; clear:both;} .form-actions { width:620px; margin:0 auto;} </style> </body> </html> 2、从优酷上获取所上传视频的状态,以及删除视频,播放视频 由于在ie游览器中优酷返回的json时,ie直接提示下载而不是返回到ajax的success中的data的情况,所有借组httpCilent模拟请求 2、1定义优酷中的应用id //应用Id var client_id = "3f55944758a967be"; var access_token = "feb81d9c7eff2b440d302770a4f389d5"; 2.2 获取视频状态 /** * 加载视频状态 */ function loadVideoStatus() { //判断视频的状态 if(videoStatus!=-1&&videoStatus!=3&&videoStatus!=2){ var jobSooId = $("#jobSoo_id_hidden").val(); $.ajax({ // 请求URl url :  "jobSoo/updateVideoStatus", // 请求参数 data : { "client_id" : client_id, "video_id" : videoId, "jobSooId":jobSooId }, // 数据类型 dataType : 'json', // 请求方式 type : 'POST', // 成功回调函数 success : function(data) { //清空 $("#shipin_show").html(""); $("#shipin_button").html(""); var html = "";//图片 var buttonHtml ="";//按钮 //审核中 if(data==1){ html = "<img  src='images/shipin_shenhe.gif' />"; buttonHtml = "<input id='video_jobSoo_delete' type='button' value='删除' onclick='deleteVideo()' class='Shielding_Enterprises_save' />"; }//已屏蔽 else if(data==2){ html = "<img  src='images/shipin_pingbi.gif' />"; buttonHtml = "<input id='video_jobSoo_delete' type='button' value='删除' onclick='deleteVideo()' class='Shielding_Enterprises_save' />"; }//正常 else if(data==3){ html = "<img id='youku_loading' src='images/youku_loading.gif' width='344' height='205'/><div id='youkuplayer' style='display:none;margin: 10px 200px; width: 300px; height: 270px'></div>"; buttonHtml = "<input id='video_jobSoo_delete' type='button' value='删除' onclick='deleteVideo()' class='Shielding_Enterprises_save' style='display:none;' />"; loadScript("http://player.youku.com/jsapi",playVideo); }//转码中 else if(data==0){ html = "<img  src='images/shipin_zhuanma.gif' />"; } $("#shipin_show").html(html); $("#shipin_button").html(buttonHtml); }, error : function(xhr) { // 跳转错误页面 window.location.href = basePath + "index.jsp"; } }); } } 2.2删除视频 /** * 删除视频 */ function deleteVideo() { if (window.confirm("你确定要删除该视频内容吗?一旦删除将不可恢复")) { //获取求职秀Id var jobSooId = $("#jobSoo_id_hidden").val(); $.ajax({ url : path + "jobSoo/deleteVideo", data : { "client_id" : client_id, "access_token" : access_token, "video_id" : videoId, "jobSooId" : jobSooId }, dataType : 'json', type : 'POST', success : function(data) { if(data){ $("#shipin_show").html(""); $("#shipin_button").html(""); var html = "<img id='video_img'  src='images/shipin_01.gif' />"; var buttonHtml = "<input id='video_jobSoo'  type='button' value='上传' onclick='toUploadVideo()' class='Shielding_Enterprises_save' />"+ "<input id='makeVideo_btn'  type='button' value='录制' class='Shielding_Enterprises_save' onclick='toMakeVideo()' />"; $("#shipin_show").html(html); $("#shipin_button").html(buttonHtml); } } }); } } 3、util代码 package com.tarena.hr.util; import java.io.File; import java.io.IOException; import java.util.Random; import net.sf.json.JSONObject; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tarena.hr.dao.ResumeDao; import com.tarena.hr.entity.Resume; import com.tarena.hr.entity.noTable.YouKuJsonBean; /** * 读取优酷平台数据的工具类 * @author 达内--教学支持与督导部--软件研发团队 * @version v1.0 2014-07-07 * */ public class YouKuUtil { private static ResumeDao resumeDao;//求职秀Dao static{ ApplicationContext  app = new ClassPathXmlApplicationContext("applicationContext.xml"); resumeDao = (ResumeDao)app.getBean("resumeDao"); } /** * 读取优酷提供的查询视频状态的json内容 * @param client_id 应用Key * @param video_id 视频ID * @return json对象 */ public static Object getVideoStatus(String client_id,String video_id){ //构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // 创建 GET方法的实例 GetMethod getMethod = new GetMethod("https://openapi.youku.com/v2/videos/show_basic.json?client_id="+client_id+"&video_id="+video_id+"&random="+(new Random().nextInt(1000))); //使用系统提供的默认的恢复策略 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { //执行getMethod int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { return null; } //读取内容 byte[] responseBody = getMethod.getResponseBody(); //处理内容 return new String(responseBody,"utf-8"); } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); return null; } catch (IOException e) { // 发生网络异常 e.printStackTrace(); return null; } finally { //释放连接 getMethod.releaseConnection(); } } /** * 删除优酷平台上的视频 * @param client_id 应用Key * @param video_id 视频ID * @param access_token OAuth2授权 * @return json对象 */ public static String deleteVideoJson(String client_id, String video_id, String access_token) { //构造HttpClient的实例 HttpClient httpClient = new HttpClient(); String url  =   " https://openapi.youku.com/v2/videos/destroy.json " ; //获取post方法实例 PostMethod postMethod  =   new  PostMethod(url); // 填入各个表单域的值 NameValuePair[] data = { new NameValuePair("client_id", client_id), new NameValuePair("access_token", access_token), new NameValuePair("video_id", video_id) }; // 将表单的值放入postMethod中 postMethod.setRequestBody(data); try { // 执行postMethod httpClient.executeMethod(postMethod); //打印结果页面 String response =   new String(postMethod.getResponseBodyAsString().getBytes("8859_1"),"utf-8"); return response; } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); return null; } catch (IOException e) { // 发生网络异常 e.printStackTrace(); return null; }finally { //释放连接 postMethod.releaseConnection(); } } /** * 上传创建接口,用于提交将要上传视频的信息 * @param client_id 客户Key * @param access_token 客户口令 * @param filepath 文件路径 * @return json对象 */ public static Object uploadFile(String client_id,String access_token,String filepath,Resume resume){ File file = new File(filepath); //构造HttpClient的实例 HttpClient httpClient = new HttpClient(); //获取文件名 String file_name = file.getName(); //获取文件大小 int file_size = new Long(file.length()).intValue(); //获取文件的md5值 String file_md5 = MD5Util.getFileMD5(file); // 创建 GET方法的实例 //System.out.println("文件名--"+file_name+"文件大小--"+file_size+"file的MD5值--"+file_md5); String title ="Tarena_"+resume.getUserId()+"_"+resume.getId()+"_jobshow"; String tags = "Tarena"; String url = "https://openapi.youku.com/v2/uploads/create.json?client_id="+client_id+"&access_token="+access_token+"&title="+title+"&tags="+tags+"&file_name="+file_name+"&file_md5="+file_md5+"&file_size="+file_size; System.out.println(url); GetMethod getMethod = new GetMethod(url); //使用系统提供的默认的恢复策略 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { //执行getMethod int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } //读取内容 byte[] responseBody = getMethod.getResponseBody(); //处理内容 System.out.println("获取json的数据为---------"+new String(responseBody,"utf-8")); return new String(responseBody,"utf-8"); } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("Please check your provided http address!"); e.printStackTrace(); return null; } catch (IOException e) { // 发生网络异常 e.printStackTrace(); return null; } finally { //释放连接 getMethod.releaseConnection(); } } /** * 用于真实上传的接口 * @param client_id 客户Key * @param access_token 客户口令 * @param filepath 文件路径 * @return json对象 */ public static Boolean commitUploadFile(String client_id,String access_token,String filepath,String parameter){ //获取jobSoo对象 Resume resume = resumeDao.findResumeByUserId(Integer.parseInt(parameter.split("_")[1])); //构造HttpClient的实例 HttpClient httpClient = new HttpClient(); String url  =   " https://openapi.youku.com/v2/uploads/commit.json " ; //获取post方法实例 PostMethod postMethod  =   new  PostMethod(url); Object json = uploadFile(client_id,access_token,filepath,resume); //将字符串转换为json对象 JSONObject obj = JSONObject.fromObject(json); //将json对象转换为javaBean对象 YouKuJsonBean bean = (YouKuJsonBean) JSONObject.toBean(obj,YouKuJsonBean.class); //获取上传token String upload_token = bean.getUpload_token(); // 填入各个表单域的值 NameValuePair[] data = {new NameValuePair("access_token", access_token), new NameValuePair("client_id", client_id), new NameValuePair("upload_token", upload_token) }; // 将表单的值放入postMethod中 postMethod.setRequestBody(data); try { // 执行postMethod httpClient.executeMethod(postMethod); //打印结果页面 String response =   new String(postMethod.getResponseBodyAsString().getBytes("8859_1"),"utf-8"); //{"video_id":"XNzM4MDQxMTAw"} //处理数据 String videoId = response.split(":")[1].substring(1, response.split(":")[1].length()-2); resume.setVideoId(videoId); resume.setVideoStatus(0); //更新jobSoo信息 resumeDao.updateResume(resume); return true; } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("Please check your provided http address!"); e.printStackTrace(); return false; } catch (IOException e) { // 发生网络异常 e.printStackTrace(); return false; } } }

你可能感兴趣的:(java,js,jquery,视频,优酷视频接口)