Wrapper around the Jsoup connection methods. Benefit is retry logic.
| 30 | * Benefit is retry logic. |
| 31 | */ |
| 32 | public class Http { |
| 33 | |
| 34 | private static final int TIMEOUT = Utils.getConfigInteger("page.timeout", 5 * 1000); |
| 35 | private static final Logger logger = LogManager.getLogger(Http.class); |
| 36 | |
| 37 | private int retries; |
| 38 | private int retrySleep = 0; |
| 39 | private final String url; |
| 40 | private Connection connection; |
| 41 | |
| 42 | // Constructors |
| 43 | public Http(String url) { |
| 44 | this.url = url; |
| 45 | defaultSettings(); |
| 46 | } |
| 47 | |
| 48 | private Http(URL url) { |
| 49 | this.url = url.toExternalForm(); |
| 50 | defaultSettings(); |
| 51 | } |
| 52 | |
| 53 | public static Http url(String url) { |
| 54 | return new Http(url); |
| 55 | } |
| 56 | |
| 57 | public static Http url(URL url) { |
| 58 | return new Http(url); |
| 59 | } |
| 60 | |
| 61 | private void defaultSettings() { |
| 62 | this.retries = Utils.getConfigInteger("download.retries", 3); |
| 63 | this.retrySleep = Utils.getConfigInteger("download.retry.sleep", 5000); |
| 64 | connection = Jsoup.connect(this.url); |
| 65 | connection.userAgent(AbstractRipper.USER_AGENT); |
| 66 | connection.method(Method.GET); |
| 67 | connection.timeout(TIMEOUT); |
| 68 | connection.maxBodySize(0); |
| 69 | |
| 70 | // Extract cookies from config entry: |
| 71 | // Example config entry: |
| 72 | // cookies.reddit.com = reddit_session=<value>; other_cookie=<value> |
| 73 | connection.cookies(cookiesForURL(this.url)); |
| 74 | } |
| 75 | |
| 76 | private Map<String, String> cookiesForURL(String u) { |
| 77 | Map<String, String> cookiesParsed = new HashMap<>(); |
| 78 | |
| 79 | String cookieDomain = ""; |
| 80 | try { |
| 81 | URL parsed = new URI(u).toURL(); |
| 82 | String cookieStr = ""; |
| 83 | |
| 84 | String[] parts = parsed.getHost().split("\\."); |
| 85 | |
| 86 | // if url is www.reddit.com, we should also use cookies from reddit.com; |
| 87 | // this rule is applied for all subdomains (for all rippers); e.g. also |
| 88 | // old.reddit.com, new.reddit.com |
| 89 | while (parts.length > 1) { |
nothing calls this directly
no test coverage detected