11package app .revanced .integrations .requests ;
22
33import org .json .JSONArray ;
4+ import org .json .JSONException ;
45import org .json .JSONObject ;
56
67import java .io .BufferedReader ;
@@ -24,32 +25,58 @@ public static HttpURLConnection getConnectionFromRoute(String apiUrl, Route rout
2425 return connection ;
2526 }
2627
28+ /**
29+ * Parse, and then disconnect the {@link HttpURLConnection}
30+ *
31+ * TODO: rename this to #parseJsonAndDisconnect
32+ */
2733 public static String parseJson (HttpURLConnection connection ) throws IOException {
28- return parseJson (connection .getInputStream (), false );
34+ String result = parseJson (connection .getInputStream (), false );
35+ connection .disconnect ();
36+ return result ;
2937 }
3038
39+ /**
40+ * Parse, and then close the {@link InputStream}
41+ *
42+ * TODO: rename this to #parseJsonAndCloseStream
43+ */
3144 public static String parseJson (InputStream inputStream , boolean isError ) throws IOException {
32- StringBuilder jsonBuilder = new StringBuilder ();
33- BufferedReader reader = new BufferedReader (new InputStreamReader (inputStream ));
34- String line ;
35- while ((line = reader .readLine ()) != null ) {
36- jsonBuilder .append (line );
37- if (isError )
38- jsonBuilder .append ("\n " );
45+ try (BufferedReader reader = new BufferedReader (new InputStreamReader (inputStream ))) {
46+ StringBuilder jsonBuilder = new StringBuilder ();
47+ String line ;
48+ while ((line = reader .readLine ()) != null ) {
49+ jsonBuilder .append (line );
50+ if (isError )
51+ jsonBuilder .append ("\n " );
52+ }
53+ return jsonBuilder .toString ();
3954 }
40- inputStream .close ();
41- return jsonBuilder .toString ();
4255 }
4356
57+ /**
58+ * Parse, and then do NOT disconnect the {@link HttpURLConnection}
59+ */
4460 public static String parseErrorJson (HttpURLConnection connection ) throws IOException {
61+ // TODO: make this also disconnect, and rename method to #parseErrorJsonAndDisconnect
4562 return parseJson (connection .getErrorStream (), true );
4663 }
4764
48- public static JSONObject getJSONObject (HttpURLConnection connection ) throws Exception {
65+ /**
66+ * Parse, and then disconnect the {@link HttpURLConnection}
67+ *
68+ * TODO: rename this to #getJSONObjectAndDisconnect
69+ */
70+ public static JSONObject getJSONObject (HttpURLConnection connection ) throws JSONException , IOException {
4971 return new JSONObject (parseJsonAndDisconnect (connection ));
5072 }
5173
52- public static JSONArray getJSONArray (HttpURLConnection connection ) throws Exception {
74+ /**
75+ * Parse, and then disconnect the {@link HttpURLConnection}
76+ *
77+ * TODO: rename this to #getJSONArrayAndDisconnect
78+ */
79+ public static JSONArray getJSONArray (HttpURLConnection connection ) throws JSONException , IOException {
5380 return new JSONArray (parseJsonAndDisconnect (connection ));
5481 }
5582
0 commit comments