Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getErrorStream.

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:com.hackerati.android.user_sdk.volley.HHurlStack.java

/**
 * Initializes an {@link HttpEntity} from the given
 * {@link HttpURLConnection}./* ww w  . java  2s.c  o  m*/
 * 
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(final HttpURLConnection connection) {
    final BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (final IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:net.daporkchop.porkbot.util.HTTPUtils.java

private static String sendRequest(HttpURLConnection connection) throws IOException {
    InputStream inputStream = null;
    try {/*  w  w w.  j  a  v  a 2 s  . c o m*/
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:bolts.WebViewAppLinkResolver.java

/**
 * Gets a string with the proper encoding (including using the charset specified in the MIME type
 * of the request) from a URLConnection.
 *///  w  w w .j a  va  2s  .c  o m
private static String readFromConnection(URLConnection connection) throws IOException {
    InputStream stream;
    if (connection instanceof HttpURLConnection) {
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        try {
            stream = connection.getInputStream();
        } catch (Exception e) {
            stream = httpConnection.getErrorStream();
        }
    } else {
        stream = connection.getInputStream();
    }
    try {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int read = 0;
        while ((read = stream.read(buffer)) != -1) {
            output.write(buffer, 0, read);
        }
        String charset = connection.getContentEncoding();
        if (charset == null) {
            String mimeType = connection.getContentType();
            String[] parts = mimeType.split(";");
            for (String part : parts) {
                part = part.trim();
                if (part.startsWith("charset=")) {
                    charset = part.substring("charset=".length());
                    break;
                }
            }
            if (charset == null) {
                charset = "UTF-8";
            }
        }
        return new String(output.toByteArray(), charset);
    } finally {
        stream.close();
    }
}

From source file:com.facebook.GraphResponse.java

@SuppressWarnings("resource")
static List<GraphResponse> fromHttpConnection(HttpURLConnection connection, GraphRequestBatch requests) {
    InputStream stream = null;/*  w w w  . j  a va 2 s .co  m*/

    try {
        if (connection.getResponseCode() >= 400) {
            stream = connection.getErrorStream();
        } else {
            stream = connection.getInputStream();
        }

        return createResponsesFromStream(stream, connection, requests);
    } catch (FacebookException facebookException) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException);
        return constructErrorResponses(requests, connection, facebookException);
    } catch (JSONException exception) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
        return constructErrorResponses(requests, connection, new FacebookException(exception));
    } catch (IOException exception) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
        return constructErrorResponses(requests, connection, new FacebookException(exception));
    } catch (SecurityException exception) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
        return constructErrorResponses(requests, connection, new FacebookException(exception));
    } finally {
        Utility.closeQuietly(stream);
    }
}

From source file:net.servicestack.client.JsonServiceClient.java

public static RuntimeException createException(HttpURLConnection res, int responseCode) {

    WebServiceException webEx = null;
    try {//from  w w w  . j a  v a 2 s . c  o  m
        String responseBody = Utils.readToEnd(res.getErrorStream(), UTF8.name());
        webEx = new WebServiceException(responseCode, res.getResponseMessage(), responseBody);

        if (Utils.matchesContentType(res.getHeaderField(HttpHeaders.ContentType), MimeTypes.Json)) {
            JSONObject jResponse = new JSONObject(responseBody);

            Iterator<?> keys = jResponse.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String varName = Utils.sanitizeVarName(key);
                if (varName.equals("responsestatus")) {
                    webEx.setResponseStatus(Utils.createResponseStatus(jResponse.get(key)));
                    break;
                }
            }
        }

        return webEx;

    } catch (IOException e) {
        if (webEx != null) {
            return webEx;
        }
        return new RuntimeException(e);
    } catch (JSONException e) {
        if (webEx != null) {
            return webEx;
        }
        return new RuntimeException(e);
    }
}

From source file:com.vaguehope.onosendai.util.HttpHelper.java

private static String summariseHttpErrorResponse(final HttpURLConnection connection) throws IOException {
    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_NOT_FOUND)
        return String.format("HTTP %s %s", responseCode, connection.getResponseMessage());
    return String.format("HTTP %s %s: %s", responseCode, connection.getResponseMessage(),
            IoHelper.toString(connection.getErrorStream(), MAX_ERR_BODY_LENGTH_CHAR));
}

From source file:dk.nsi.minlog.test.utils.TestHelper.java

public static String sendRequest(String url, String action, String docXml, boolean failOnError)
        throws IOException, ServiceException {
    URL u = new URL(url);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setDoOutput(true);//from   w  ww  .  j a  va2s  .  com
    uc.setDoInput(true);
    uc.setRequestMethod("POST");
    uc.setRequestProperty("SOAPAction", "\"" + action + "\"");
    uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;");
    OutputStream os = uc.getOutputStream();

    IOUtils.write(docXml, os, "UTF-8");
    os.flush();
    os.close();

    InputStream is;
    if (uc.getResponseCode() != 200) {
        is = uc.getErrorStream();
    } else {
        is = uc.getInputStream();
    }
    String res = IOUtils.toString(is);

    is.close();
    if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) {
        throw new ServiceException(res);
    }
    uc.disconnect();

    return res;
}

From source file:org.apache.giraph.rexster.utils.RexsterUtils.java

/**
 * Utility to handle the output response in case of errors.
 *
 * @param conn connection to the Rexster Interface
 * @param type type of data saved (vertices or edges)
 *///from  w  ww. j  av a  2  s  .c om
private static void handleResponse(HttpURLConnection conn, String type)
        throws IOException, InterruptedException {

    if (conn.getResponseCode() != 200) {
        InputStream is = conn.getErrorStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

        JSONObject obj = new JSONObject(rd);
        StringBuffer sb = new StringBuffer("Error occured while saving " + type + ";");
        String aux;
        while ((aux = rd.readLine()) != null) {
            sb.append(aux);
        }
        sb.append(obj);

        /*
        try {
          LOG.info("--> " + obj);
          String message = obj.getString("message");
          sb.append(" ");
          sb.append(message);
        } catch (JSONException e) {
          LOG.error("Unable to extract the error message.");
        }
        */
        rd.close();

        throw new InterruptedException(sb.toString());
    }
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

private static void validateConnectionAfterUpload(final HttpURLConnection connection) throws IOException {

    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
        try (final InputStream is = connection.getInputStream()) {
            while (is.read() > 0) {
                // consume
            }/*from  w  w w.  j  a va  2s . com*/
        }
    } else {
        try (final InputStream is = connection.getErrorStream()) {
            final String error = IOUtils.toString(is);
            throw new IOException(String.format("Unable to upload file. Got error %d %s: %s", responseCode,
                    connection.getResponseMessage(), error));
        }
    }
    connection.disconnect();
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a GET request to the specified URL and returns the result.
 * <p />/*from  w  ww .  j a v  a2s .  com*/
 * The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url URL to submit the GET request to
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performGetRequest(final URL url) throws IOException {
    Validate.notNull(url);
    final HttpURLConnection connection = createUrlConnection(url);

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}