通过JAVA获取优酷视频,现在很多社会网站都有这个功能,用户输入优酷视频地址后,能找到对应的视频及视频的缩略图,有些社区网站还能获取到视频的时长。
比如:新浪微博就有这个功能,当用户输入视频网址后,就能获取到相应的视频地址及视频的缩略图。
01 import java.io.IOException;
02 import java.io.UnsupportedEncodingException;
03 import java.net.MalformedURLException;
04
05 import org.jsoup.Jsoup;
06 import org.jsoup.nodes.Document;
07 import org.jsoup.nodes.Element;
08
09
10 /**
11 * 获取优酷视频
12 * @author sunlightcs
13 * 2011-3-29
14 * http://hi.juziku.com/sunlightcs/
15 */
16 public class VideoTest {
17
18 public static void main(String[] args) throws Exception{
19 String pic = getElementAttrById("s_sina", "href");
20 int local = pic.indexOf("pic=");
21 pic = pic.substring(local+4);
22 System.out.println("视频缩略图:"+pic);
23
24
25 String flashUrl = getElementAttrById("link2", "value");
26 System.out.println("视频地址:"+flashUrl);
27
28
29 String time = getElementAttrById("download", "href");
30 String []arrays = time.split("\\|");
31 time = arrays[4];
32 System.out.println("视频时长:"+time);
33
34 }
35
36
37 /**
38 * 根据HTML的ID键及属于名,获取属于值
39 * @param id HTML的ID键
40 * @param attrName 属于名
41 * @return 返回属性值
42 */
43 private static String getElementAttrById(String id, String attrName)throws Exception{
44 Document doc = getURLContent();
45 Element et = doc.getElementById(id);
46 String attrValue = et.attr(attrName);
47
48 return attrValue;
49 }
50
51
52
53 /**
54 * 获取优酷网页的内容
55 */
56 private static Document getURLContent() throws MalformedURLException, IOException, UnsupportedEncodingException {
57 Document doc = Jsoup.connect("http://v.youku.com/v_show/id_XMjU0MjI2NzY0.html")
58 .data("query", "Java")
59 .userAgent("Mozilla")
60 .cookie("auth", "token")
61 .timeout(3000)
62 .post();
63 return doc;
64 }
65
66 }
用到的jar包
jsoup-1.5.2.jar