5
5
import com .google .gson .JsonParser ;
6
6
7
7
import org .jetbrains .annotations .NotNull ;
8
- import org .jetbrains .annotations .Nullable ;
9
8
10
9
import java .io .BufferedReader ;
11
10
import java .io .IOException ;
12
11
import java .io .InputStreamReader ;
13
12
import java .net .HttpURLConnection ;
14
13
import java .net .URI ;
14
+ import java .util .Optional ;
15
15
import java .util .function .Function ;
16
16
import java .util .stream .Collectors ;
17
17
@@ -31,21 +31,21 @@ public class HttpUtility {
31
31
*
32
32
* @return the result of the specified function, or null if the request failed
33
33
*/
34
- @ Nullable
35
- public static <T > T get (@ NotNull String userAgent , @ NotNull String url , Function <InputStreamReader , T > function ) {
34
+ @ NotNull
35
+ public static <T > Optional < T > get (@ NotNull String userAgent , @ NotNull String url , Function <InputStreamReader , T > function ) {
36
36
T result = null ;
37
37
HttpURLConnection connection = null ;
38
38
try {
39
39
connection = (HttpURLConnection ) URI .create (url ).toURL ().openConnection ();
40
40
connection .setRequestMethod ("GET" );
41
41
connection .setRequestProperty ("User-Agent" , userAgent );
42
- if (connection .getResponseCode () == 404 ) return null ;
42
+ if (connection .getResponseCode () == 404 ) return Optional . empty () ;
43
43
result = function .apply (new InputStreamReader (connection .getInputStream ()));
44
44
} catch (final IOException ignored ) {
45
45
// Ignored
46
46
}
47
47
if (connection != null ) connection .disconnect ();
48
- return result ;
48
+ return Optional . ofNullable ( result ) ;
49
49
}
50
50
51
51
/**
@@ -56,8 +56,8 @@ public static <T> T get(@NotNull String userAgent, @NotNull String url, Function
56
56
*
57
57
* @return the {@link String}, or null if the request failed
58
58
*/
59
- @ Nullable
60
- public static String getString (@ NotNull String userAgent , @ NotNull String urlString ) {
59
+ @ NotNull
60
+ public static Optional < String > getString (@ NotNull String userAgent , @ NotNull String urlString ) {
61
61
return get (userAgent , urlString , reader -> new BufferedReader (reader ).lines ().collect (Collectors .joining ("\n " )));
62
62
}
63
63
@@ -69,8 +69,8 @@ public static String getString(@NotNull String userAgent, @NotNull String urlStr
69
69
*
70
70
* @return the {@link JsonElement} retrieved from the specified URL
71
71
*/
72
- @ Nullable
73
- public static JsonElement getJson (@ NotNull String userAgent , @ NotNull String urlString ) {
72
+ @ NotNull
73
+ public static Optional < JsonElement > getJson (@ NotNull String userAgent , @ NotNull String urlString ) {
74
74
return get (userAgent , urlString , reader -> new JsonParser ().parse (reader ));
75
75
}
76
76
0 commit comments