@@ -63,6 +63,9 @@ public final class HttpOpener extends DefaultObjectPipe<String, ObjectReceiver<R
6363
6464 private static final Method DEFAULT_METHOD = Method .GET ;
6565
66+ private static final int SUCCESS_CODE_MIN = 200 ;
67+ private static final int SUCCESS_CODE_MAX = 399 ;
68+
6669 private final Map <String , String > headers = new HashMap <>();
6770
6871 private Method method ;
@@ -237,20 +240,8 @@ public void process(final String input) {
237240 }
238241
239242 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 );
254245
255246 final String contentEncoding = getEncoding (connection .getContentEncoding ());
256247 getReceiver ().process (new InputStreamReader (inputStream , contentEncoding ));
@@ -277,6 +268,42 @@ else if (inputUsed) {
277268 return result ;
278269 }
279270
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+
280307 private String getEncoding (final String contentEncoding ) {
281308 return contentEncoding != null ? contentEncoding : headers .get (ENCODING_HEADER );
282309 }
0 commit comments