@@ -63,6 +63,9 @@ public final class HttpOpener extends DefaultObjectPipe<String, ObjectReceiver<R
63
63
64
64
private static final Method DEFAULT_METHOD = Method .GET ;
65
65
66
+ private static final int SUCCESS_CODE_MIN = 200 ;
67
+ private static final int SUCCESS_CODE_MAX = 399 ;
68
+
66
69
private final Map <String , String > headers = new HashMap <>();
67
70
68
71
private Method method ;
@@ -237,20 +240,8 @@ public void process(final String input) {
237
240
}
238
241
239
242
final InputStream errorStream = connection .getErrorStream ();
240
- final InputStream inputStream ;
241
-
242
- if (errorStream != null ) {
243
- if (errorPrefix != null ) {
244
- final InputStream errorPrefixStream = new ByteArrayInputStream (errorPrefix .getBytes ());
245
- inputStream = new SequenceInputStream (errorPrefixStream , errorStream );
246
- }
247
- else {
248
- inputStream = errorStream ;
249
- }
250
- }
251
- else {
252
- inputStream = connection .getInputStream ();
253
- }
243
+ final InputStream inputStream = errorStream != null ?
244
+ getErrorStream (errorStream ) : getInputStream (connection );
254
245
255
246
final String contentEncoding = getEncoding (connection .getContentEncoding ());
256
247
getReceiver ().process (new InputStreamReader (inputStream , contentEncoding ));
@@ -277,6 +268,42 @@ else if (inputUsed) {
277
268
return result ;
278
269
}
279
270
271
+ private InputStream getInputStream (final HttpURLConnection connection ) throws IOException {
272
+ try {
273
+ return connection .getInputStream ();
274
+ }
275
+ catch (final IOException e ) {
276
+ final int responseCode = connection .getResponseCode ();
277
+ if (responseCode >= SUCCESS_CODE_MIN && responseCode <= SUCCESS_CODE_MAX ) {
278
+ throw e ;
279
+ }
280
+ else {
281
+ final StringBuilder sb = new StringBuilder (String .valueOf (responseCode ));
282
+
283
+ final String responseMessage = connection .getResponseMessage ();
284
+ if (responseMessage != null ) {
285
+ sb .append (" - " ).append (responseMessage );
286
+ }
287
+
288
+ return getErrorStream (getInputStream (sb .toString ()));
289
+ }
290
+ }
291
+ }
292
+
293
+ private InputStream getInputStream (final String string ) {
294
+ return new ByteArrayInputStream (string .getBytes ());
295
+ }
296
+
297
+ private InputStream getErrorStream (final InputStream errorStream ) {
298
+ if (errorPrefix != null ) {
299
+ final InputStream errorPrefixStream = getInputStream (errorPrefix );
300
+ return new SequenceInputStream (errorPrefixStream , errorStream );
301
+ }
302
+ else {
303
+ return errorStream ;
304
+ }
305
+ }
306
+
280
307
private String getEncoding (final String contentEncoding ) {
281
308
return contentEncoding != null ? contentEncoding : headers .get (ENCODING_HEADER );
282
309
}
0 commit comments