2012年7月17日 星期二

How to get Youtube MP4 video using java?



import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class Parser {

private static String vid="c2ovrKzRezw";
private static String url="http://www.youtube.com/get_video_info?video_id="+vid;//xzWJvDTfWyc";

static String pattern3="video/mp4";
public static void main(String args[]){
try {
String result= getMessageFromUrl(url);
//System.err.println(result);
String p_result=java.net.URLDecoder.decode(java.net.URLDecoder.decode(result, "UTF-8"),"UTF-8");
//結果太長了, 沒研究是否可以用正規表示式處理, 先用暴力方法解決
  // if somebody know how to use reg press to parse the result, please let me know.
// currently, I just hard code to parse mp4 url
int last=p_result.lastIndexOf("type=video/mp4");
String s2= p_result.substring(0,last+15);
int lasthttp= s2.lastIndexOf("http://");
String mp4Url=s2.substring(lasthttp, s2.length()-1);
System.err.println(mp4Url);
//ok, now save it to disk
File f= new File("d:\\"+vid+".mp4");
org.apache.commons.io.FileUtils.copyURLToFile(new URL(mp4Url),f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static String getMessageFromUrl(String msgUrl) throws IOException {
URL url = new URL(msgUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String inputLine;
StringBuffer sb = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
return sb.toString();
}

}

that means you can also save youtube video in your android app.
but 18+ video can't be download, it may need to integrate with youtube api to download 18+ video.



1 則留言: