From 4a45407e01ae13e7830815ac720e2fd2b42e902e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Konieczny?= Date: Sun, 3 Mar 2024 11:51:56 +0100 Subject: [PATCH] - Added a fix for Reddit 403'ing the bot, by including a user-agent header impersonating a Firefox client --- src/main/java/com/eukon05/dilanbot/reddit/RedditService.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/eukon05/dilanbot/reddit/RedditService.java b/src/main/java/com/eukon05/dilanbot/reddit/RedditService.java index 438e7fd..a83bade 100644 --- a/src/main/java/com/eukon05/dilanbot/reddit/RedditService.java +++ b/src/main/java/com/eukon05/dilanbot/reddit/RedditService.java @@ -18,6 +18,8 @@ public class RedditService { private final Gson gson; private final HttpClient client = HttpClient.newHttpClient(); private static final String REDDIT_API_URL = "https://www.reddit.com/r/%s/randomrising.json?limit=1"; + private static final String MOZILLA_USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0"; + private static final String USER_AGENT_HEADER = "User-Agent"; public RedditService(Gson gson) { this.gson = gson; @@ -26,6 +28,7 @@ public RedditService(Gson gson) { RedditSubmission getRandomSubmission(String subredditName) throws IOException, InterruptedException { HttpResponse response = client.send(HttpRequest .newBuilder() + .setHeader(USER_AGENT_HEADER, MOZILLA_USER_AGENT) .uri(URI.create(String.format(REDDIT_API_URL, URLEncoder.encode(subredditName, StandardCharsets.UTF_8)))) .build(), HttpResponse.BodyHandlers.ofString());