22
33import javax .annotation .Nonnull ;
44import javax .annotation .Nullable ;
5+ import java .util .Arrays ;
56import java .util .Collections ;
67import java .util .List ;
78import java .util .Map ;
89
910import org .schabi .newpipe .extractor .exceptions .HttpResponseException ;
10- import org .schabi .newpipe .extractor .utils .HttpUtils ;
1111
1212/**
1313 * A Data class used to hold the results from requests made by the Downloader implementation.
@@ -33,6 +33,28 @@ public Response(final int responseCode,
3333 this .latestUrl = latestUrl ;
3434 }
3535
36+ /**
37+ * Validates the response codes for the given {@link Response}, and throws
38+ * a {@link HttpResponseException} if the code is invalid
39+ * @param response The response to validate
40+ * @param validResponseCodes Expected valid response codes
41+ * @throws HttpResponseException Thrown when the response code is not in {@code validResponseCodes},
42+ * or when {@code validResponseCodes} is empty and the code is a 4xx or 5xx error.
43+ */
44+ // CHECKSTYLE:ON
45+ public static void validateResponseCode (final Response response ,
46+ final int ... validResponseCodes )
47+ throws HttpResponseException {
48+ final int code = response .responseCode ();
49+ final var throwError = (validResponseCodes == null || validResponseCodes .length == 0 )
50+ ? code >= 400 && code <= 599
51+ : Arrays .stream (validResponseCodes ).noneMatch (c -> c == code );
52+
53+ if (throwError ) {
54+ throw new HttpResponseException (response );
55+ }
56+ }
57+
3658 public int responseCode () {
3759 return responseCode ;
3860 }
@@ -83,12 +105,13 @@ public String getHeader(final String name) {
83105
84106 return null ;
85107 }
108+
86109 // CHECKSTYLE:OFF
87110 /**
88111 * Helper function simply to make it easier to validate response code inline
89112 * before getting the code/body/latestUrl/etc.
90113 * Validates the response codes for the given {@link Response}, and throws a {@link HttpResponseException} if the code is invalid
91- * @see HttpUtils #validateResponseCode(Response, int...)
114+ * @see Response #validateResponseCode(Response, int...)
92115 * @param validResponseCodes Expected valid response codes
93116 * @return {@link this} response
94117 * @throws HttpResponseException Thrown when the response code is not in {@code validResponseCodes},
@@ -97,7 +120,7 @@ public String getHeader(final String name) {
97120 // CHECKSTYLE:ON
98121 public Response validateResponseCode (final int ... validResponseCodes )
99122 throws HttpResponseException {
100- HttpUtils . validateResponseCode (this , validResponseCodes );
123+ validateResponseCode (this , validResponseCodes );
101124 return this ;
102125 }
103126}
0 commit comments