11package YouTubeSearchApi ;
22
33import YouTubeSearchApi .entity .YoutubeVideo ;
4+ import YouTubeSearchApi .exception .NoResultFoundException ;
45import YouTubeSearchApi .utility .Utils ;
56import com .google .gson .Gson ;
67import com .google .gson .JsonArray ;
@@ -21,13 +22,26 @@ public YoutubeClient() {
2122 this .YOUTUBE_BASE_URL = "https://www.youtube.com/" ;
2223 }
2324
24- public List <YoutubeVideo > search (String keywords , int maxResults ) throws IOException {
25+ public List <YoutubeVideo > search (String keywords , int maxResults ) throws IOException , NoResultFoundException {
26+ String startFeature = "window[\" ytInitialData\" ]" ;
2527 String encodedKeywords = URLEncoder .encode (keywords , StandardCharsets .UTF_8 .toString ());
2628 String searchUrl = this .YOUTUBE_BASE_URL + "results?search_query=" + encodedKeywords ;
2729
28- String pageContent = Utils .httpRequest (searchUrl );
30+ // try get feature 3 times
31+ String pageContent = "" ;
32+ boolean foundFeatureFlag = false ;
33+ for (int i = 0 ; i < 3 ; i ++) {
34+ pageContent = Utils .httpRequest (searchUrl );
35+ if (pageContent .contains (startFeature )) {
36+ foundFeatureFlag = true ;
37+ break ;
38+ }
39+ }
40+
41+ if (!foundFeatureFlag ) {
42+ throw new NoResultFoundException ("what you searched was unfortunately not found or doesn't exist. keywords" + keywords );
43+ }
2944
30- String startFeature = "window[\" ytInitialData\" ]" ;
3145
3246 // + startFeature.length() + 3. because we want to get rid of the startFeature and " = ".
3347 // And get only the Json data
0 commit comments