我试图通过API网页的帮助使用视频ID来获取youtube视频的标题。但是,我在尝试通过代码访问相同时遇到FileNotFoundException
。
我的代码如下,
String title = "";
try {
URL u = new URL("http://gdata.youtube.com/feeds/api/videos/" + videoID + "?v=2");
URLConnection uc = u.openConnection();
System.setProperty("java.net.useSystemProxies", "true");
uc.setRequestProperty("Host", "www.youtube.com");
uc.setRequestProperty("Connection", "keep-alive");
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1");
uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
uc.setRequestProperty("Accept-Encoding", "html");
uc.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
System.out.println("Retrieving video title for \"" + videoID + "\"");
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String tmp = "";
String pageResponse = "";
while ((tmp = br.readLine()) != null) {
pageResponse += tmp;
}
title = parseResponse(pageResponse, "<media:title type='plain'>", "</media:title>");//pageResponse is a method to extract the text between 2 stings
System.out.println("Title : " + title);
} catch (Exception e) {
System.out.println(e);
}
控制台输出:
http://www.youtube.com/watch?v=m7dapUWHykw
Video ID : m7dapUWHykw
http://gdata.youtube.com/feeds/api/videos/m7dapUWHykw?v=2
Retrieving video title for "m7dapUWHykw"
java.io.FileNotFoundException: http://gdata.youtube.com/feeds/api/videos/m7dapUWHykw?v=2
但如果我使用网络浏览器打开相同内容,我可以毫无问题地访问它。
有人可以告诉我代码有什么问题吗?
上述方法的PrintStackTrace如下,
java.io.FileNotFoundException: http://gdata.youtube.com/feeds/api/videos/m7dapUWHykw?v=2
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1311)
at getytv.YouTubeDownloader.getYouTubeVideoTitle(YouTubeDownloader.java:170)
at getytv.YouTubeDownloader.getYouTubeVideoDownloadLinks(YouTubeDownloader.java:276)
at getytv.GetYouTubeVideo.updateDownloadTable(GetYouTubeVideo.java:215)
at getytv.ClipBoardMonitor$1.run(ClipBoardMonitor.java:88)
提前致谢。