public static String get(URL url, final String userAgent) { return get(url, -1, userAgent); }
public static String get(URL url, int timeout, final String userAgent) { String line = ""; HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", userAgent); if (timeout > 0) { urlConnection.setConnectTimeout(timeout); } line = readLines(urlConnection); } catch (IOException ignored) { } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return line; }
private static String readLines(URLConnection connection) throws IOException { InputStream inputStream; try { inputStream = connection.getInputStream(); } catch (IndexOutOfBoundsException ignored) { // IndexOutOfBoundsException sometimes is thrown by the okHttp library // bundled within the android framework, we can only catch the exception here, // or use the latest okHttp3. return ""; } StringBuilder total = new StringBuilder(); try (BufferedReader bufferedReader = createReader(inputStream)) { String line; while ((line = bufferedReader.readLine()) != null) { total.append(line).append('\n'); } } return total.toString(); }
/** * * @param strings * strings[0] is url * strings[1] is userAgent * strings[2] is SocketTag(intString) * @return */ @Override protected String doInBackground(String... strings) { String line; try { // TODO: 8/6/18 Check range TrafficStats.setThreadStatsTag(Integer.parseInt(strings[2])); } catch (NumberFormatException ignored) { throw new IllegalArgumentException("Socket Tag should be a number"); } try { line = HttpRequest.get(new URL(strings[0]), strings[1]); } catch (MalformedURLException ex) { throw new IllegalArgumentException("MalformedURLException"); } return line; } }
private void loadFromRemote() { backgroundExecutorService.submit(() -> { TrafficStats.setThreadStatsTag(socketTag); try { Inject.sleepIfTesting(delayNetworkLoad); String string = HttpRequest.get(new URL(subscriptionUrl), userAgent); string = string.replace("\n", ""); stringLiveData.postValue(new Pair<>(ResponseData.SOURCE_NETWORK, string)); if (TextUtils.isEmpty(string)) { deleteCache(); } else { writeToCache(string); } } catch (MalformedURLException e) { e.printStackTrace(); } }); }