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.openshift.internal.restclient.http.UrlConnectionHttpClient.java

protected String createErrorMessage(IOException ioe, HttpURLConnection connection) throws IOException {
    String errorMessage = IOUtils.toString(connection.getErrorStream());
    if (!StringUtils.isEmpty(errorMessage)) {
        return errorMessage;
    }//from w w w  . j a  v a  2 s.  co m
    StringBuilder builder = new StringBuilder("Connection to ").append(connection.getURL());
    String reason = connection.getResponseMessage();
    if (!StringUtils.isEmpty(reason)) {
        builder.append(": ").append(reason);
    }
    return builder.toString();
}

From source file:org.peterbaldwin.vlcremote.sweep.Worker.java

@Override
public void run() {
    // Note: InetAddress#isReachable(int) always returns false for Windows
    // hosts because applications do not have permission to perform ICMP
    // echo requests.
    for (;;) {//  w ww. j av a  2s .co m
        byte[] ipAddress = mManager.pollIpAddress();
        if (ipAddress == null) {
            break;
        }
        try {
            InetAddress address = InetAddress.getByAddress(ipAddress);
            String hostAddress = address.getHostAddress();
            URL url = createUrl("http", hostAddress, mPort, mPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            try {
                int responseCode = connection.getResponseCode();
                String responseMessage = connection.getResponseMessage();
                InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK)
                        ? connection.getInputStream()
                        : connection.getErrorStream();
                if (inputStream != null) {
                    try {
                        int length = connection.getContentLength();
                        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
                        entity.setContentType(connection.getContentType());

                        // Copy the entire response body into memory
                        // before the HTTP connection is closed:
                        String body = EntityUtils.toString(entity);

                        ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1);
                        String hostname = address.getHostName();
                        StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage);
                        HttpResponse response = new BasicHttpResponse(statusLine);
                        response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort);
                        response.setEntity(new StringEntity(body));
                        mCallback.onReachable(ipAddress, response);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    Log.w(TAG, "InputStream is null");
                }
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            mCallback.onUnreachable(ipAddress, e);
        }
    }
}

From source file:models.cloud.notifications.gcm.Sender.java

/**
 * Sends a message without retrying in case of service unavailability.
 * /*from w  w w .jav  a 2  s  .c  om*/
 * @return {@literal true} if the message was sent successfully,
 *         {@literal false} if it failed but could be retried.
 * 
 * @throws IllegalArgumentException
 *             if registrationIds is {@literal null} or empty.
 * @throws models.cloud.notifications.gcm.exceptions.InvalidRequestException
 *             if GCM didn't returned a 200 status.
 * @throws java.io.IOException
 *             if message could not be sent or received.
 */
public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException {
    if (nonNull(registrationIds).isEmpty()) {
        throw new IllegalArgumentException("registrationIds cannot be empty");
    }

    Map<Object, Object> jsonRequest = new HashMap<>();
    setJsonField(jsonRequest, Constants.PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, Constants.PARAM_COLLAPSE_KEY, message.getCollapseKey());
    setJsonField(jsonRequest, Constants.PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    jsonRequest.put(Constants.JSON_REGISTRATION_IDS, registrationIds);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(Constants.JSON_PAYLOAD, payload);
    }
    String requestBody = Json.toJson(jsonRequest).toString();
    logger.finest("JSON request: " + requestBody);
    HttpURLConnection conn = post(Constants.GCM_SEND_ENDPOINT, "application/json;charset=utf-8;", requestBody);
    int status = conn.getResponseCode();
    String responseBody;
    if (status != 200) {
        responseBody = getString(conn.getErrorStream());
        logger.finest("JSON error response: " + responseBody);
        throw new InvalidRequestException(status, responseBody);
    }
    responseBody = getString(conn.getInputStream());
    logger.finest("JSON response: " + responseBody);
    JsonNode jsonResponse;
    try {
        jsonResponse = Json.parse(responseBody);
        int success = getNumber(jsonResponse, Constants.JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, Constants.JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, Constants.JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, Constants.JSON_MULTICAST_ID).longValue();
        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);
        JsonNode results = jsonResponse.get(Constants.JSON_RESULTS);
        if (results != null && results.isArray()) {
            for (int i = 0; i < results.size(); i++) {
                JsonNode jsonResult = results.get(i);

                Result.Builder builder1 = new Result.Builder();

                if (jsonResult.has(Constants.JSON_ERROR)) {
                    String error = jsonResult.get(Constants.JSON_ERROR).asText();
                    builder1.errorCode(error);
                } else {
                    String messageId = jsonResult.get(Constants.JSON_MESSAGE_ID).asText();
                    String canonicalRegId = null;
                    if (jsonResult.has(Constants.TOKEN_CANONICAL_REG_ID)) {
                        canonicalRegId = jsonResult.get(Constants.TOKEN_CANONICAL_REG_ID).asText();
                    }
                    builder1.messageId(messageId).canonicalRegistrationId(canonicalRegId);
                }

                Result result = builder1.build();
                builder.addResult(result);
            }
        }
        return builder.build();
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:CloudManagerAPI.java

private String readError(HttpURLConnection connection) throws IOException {
    return readBody(connection.getErrorStream());
}

From source file:com.adaptris.core.http.JdkHttpProducer.java

private void processErrorReply(HttpURLConnection http, AdaptrisMessage reply)
        throws IOException, CoreException {
    InputStream error = null;/*from www  . j  a  v  a 2  s . co  m*/
    OutputStream out = null;
    try {
        if (http.getContentLength() < TWO_MEG) {
            error = http.getErrorStream();
            out = reply.getOutputStream();
        } else {
            out = new BufferedOutputStream(reply.getOutputStream(), FOUR_MEG);
            error = new BufferedInputStream(http.getErrorStream(), FOUR_MEG);
        }
        StreamUtil.copyStream(error, out);
        if (httpHeadersAsMetadata()) {
            addReplyMetadata(http.getHeaderFields(), reply);
        }
    } finally {
        IOUtils.closeQuietly(error);
        IOUtils.closeQuietly(out);
    }
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
}

From source file:com.example.gauth.GAuthTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 *
 * @throws java.io.IOException    if communication with user info server failed.
 * @throws org.json.JSONException if the response from the server could not be parsed.
 *///from  ww w. j a v  a 2 s.c o m
private void fetchUserFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String response = readResponse(is);
        mActivity.showResult(response);
        is.close();
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
    } else {
        onError("Server returned the following error code: " + sc, null);
    }
}

From source file:babel.util.language.GoogleLangDetector.java

/**
 * Forms an HTTP request, sends it using GET method and returns the result of
 * the request as a JSONObject.//from  w ww .  ja v  a2s. c  om
 *
 * @param url the URL to query for a JSONObject.
 */
protected JSONObject retrieveJSON(final URL url) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", m_referrer);
        uc.setRequestMethod("GET");
        uc.setDoOutput(true);

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();

            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("Error retrieving detection result : " + ex.toString(), ex);
    }
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

@Override
public ListenableFuture<Response> request(final URI uri, final String method, final byte[] entityBytes,
        final Map<String, List<String>> headers) {
    return executorService.submit(new Callable<Response>() {
        @Override//from ww  w.j  a  v a  2 s  .  c om
        public Response call() throws Exception {
            final HttpURLConnection connection = connect(uri, method, entityBytes, headers);
            final int status = connection.getResponseCode();
            final InputStream rawStream;

            if (status / 100 != 2) {
                rawStream = connection.getErrorStream();
            } else {
                rawStream = connection.getInputStream();
            }

            final boolean gzip = isGzipCompressed(connection);
            final InputStream stream = gzip ? new GZIPInputStream(rawStream) : rawStream;
            final ByteArrayOutputStream payload = new ByteArrayOutputStream();
            if (stream != null) {
                int n;
                byte[] buffer = new byte[4096];
                while ((n = stream.read(buffer, 0, buffer.length)) != -1) {
                    payload.write(buffer, 0, n);
                }
            }

            URI realUri = connection.getURL().toURI();
            if (log.isTraceEnabled()) {
                log.trace("rep: {} {} {} {} {} gzip:{}", method, realUri, status, payload.size(),
                        decode(payload), gzip);
            } else {
                log.debug("rep: {} {} {} {} gzip:{}", method, realUri, status, payload.size(), gzip);
            }

            return new Response(method, uri, status, payload.toByteArray(),
                    Collections.unmodifiableMap(Maps.newHashMap(connection.getHeaderFields())));
        }

        private boolean isGzipCompressed(final HttpURLConnection connection) {
            final List<String> encodings = connection.getHeaderFields().get("Content-Encoding");
            if (encodings == null) {
                return false;
            }
            for (String encoding : encodings) {
                if ("gzip".equals(encoding)) {
                    return true;
                }
            }
            return false;
        }
    });
}

From source file:com.sound.app.auth.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws java.io.IOException if communication with user info server failed.
 * @throws org.json.JSONException if the response from the server could not be parsed.
 *//*from w w w .j  av  a  2  s.  c o  m*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();

        Auth auth = getInfo(readResponse(is));
        mActivity.next(auth);
        is.close();

    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.hdezninirola.fantasywithdrawer.utils.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws java.io.IOException if communication with user info server failed.
 * @throws org.json.JSONException if the response from the server could not be parsed.
 *///from w  w w  .j ava 2  s.  c  om
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = readResponse(is);
        mActivity.show(name);
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}