Skip to content

Commit e4cb5c9

Browse files
committed
Update YoutubeClient.search & Add exception to test case
1 parent 7362b41 commit e4cb5c9

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/main/java/YouTubeSearchApi/YoutubeClient.java

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package YouTubeSearchApi;
22

33
import YouTubeSearchApi.entity.YoutubeVideo;
4+
import YouTubeSearchApi.exception.NoResultFoundException;
45
import YouTubeSearchApi.utility.Utils;
56
import com.google.gson.Gson;
67
import 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

src/test/java/YouTubeSearchApi/TestYoutubeClientSearch.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33

44
import YouTubeSearchApi.entity.YoutubeVideo;
5+
import YouTubeSearchApi.exception.NoResultFoundException;
56

67
import java.io.IOException;
78
import java.util.ArrayList;
@@ -19,7 +20,7 @@ public static void main(String[] args) {
1920
videos = client.search("CHiCO Love Letter", 5);
2021
System.out.println(videos.size());
2122
System.out.println(videos.toString());
22-
} catch (IOException e) {
23+
} catch (IOException | NoResultFoundException e) {
2324
e.printStackTrace();
2425
}
2526

0 commit comments

Comments
 (0)