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.NotifyMe.auth.AbstractGetInfoTask.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 IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *///ww w.  ja  v  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();
        //String name = getFirstName(readResponse(is));
        //mActivity.show("Hello " + name + "!");
        mActivity.saveProfile(new JSONObject(readResponse(is)));
        is.close();
        mActivity.finishActivity();
        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;
    }
}

From source file:com.ttl.googleplus.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 IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*from   w  w  w. ja v a2s  . co  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();

        String name = getFirstName(readResponse(is));
        Log.d("profile data", readResponse(is));

        mActivity.show("Hello " + 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;
    }
}

From source file:com.nostra13.universalimageloader.core.download.BaseImageDownloader.java

/**
 * Retrieves {@link InputStream} of image by URI (image is located in the network).
 *
 * @param imageUri Image URI/*w ww .  jav  a 2s .  c  o  m*/
 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    HttpURLConnection conn = createConnection(imageUri, extra);

    int redirectCount = 0;
    while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
        conn = createConnection(conn.getHeaderField("Location"), extra);
        redirectCount++;
    }

    InputStream imageStream;
    try {
        imageStream = conn.getInputStream();
    } catch (IOException e) {
        // Read all data to allow reuse connection (http://bit.ly/1ad35PY)
        IoUtils.readAndCloseStream(conn.getErrorStream());
        throw e;
    }
    return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE),
            conn.getContentLength());
}

From source file:org.runnerup.export.GoogleFitSynchronizer.java

private Status sendData(StringWriter w, String suffix, RequestMethod method) throws IOException {
    Status status = Status.ERROR;
    for (int attempts = 0; attempts < MAX_ATTEMPTS; attempts++) {
        HttpURLConnection connect = getHttpURLConnection(suffix, method);
        GZIPOutputStream gos = new GZIPOutputStream(connect.getOutputStream());
        gos.write(w.toString().getBytes());
        gos.flush();/*  w w  w . j  av  a2s.  c  o  m*/
        gos.close();

        int code = connect.getResponseCode();
        try {
            if (code == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                continue;
            } else if (code != HttpStatus.SC_OK) {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getErrorStream())).toString());
                status = Status.ERROR;
                break;
            } else {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getInputStream())).toString());
                status = Status.OK;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            connect.disconnect();
        }
    }
    return status;
}

From source file:com.zhonghui.tool.controller.HttpClient.java

/**
 * Response?//from  w w  w.ja  v  a 2  s  .com
 *
 * @param connection 
 * @param encoding ?
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
private String response(final HttpURLConnection connection, String encoding)
        throws URISyntaxException, IOException, Exception {
    InputStream in = null;
    StringBuilder sb = new StringBuilder(1024);
    BufferedReader br = null;
    try {
        if (200 == connection.getResponseCode()) {
            in = connection.getInputStream();
            sb.append(new String(read(in), encoding));
        } else {
            in = connection.getErrorStream();
            sb.append(new String(read(in), encoding));
        }
        logger.info("HTTP Return Status-Code:[" + connection.getResponseCode() + "]");
        return sb.toString();
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != br) {
            br.close();
        }
        if (null != in) {
            in.close();
        }
        if (null != connection) {
            connection.disconnect();
        }
    }
}

From source file:br.com.great.gcm.server.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, List, int)} for more info.
 *
   * @param message mensagem/*from   ww w  .  j  a  v a  2  s  .  co m*/
   * @param registrationIds lista de dispositivos
 * @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 InvalidRequestException if GCM didn't returned a 200 status.
 * @throws 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<Object, Object>();
    setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
    setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }
    String requestBody = JSONValue.toJSONString(jsonRequest);
    logger.finest("JSON request: " + requestBody);
    HttpURLConnection conn = post(GCM_SEND_ENDPOINT, "application/json", 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);
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse;
    try {
        jsonResponse = (JSONObject) parser.parse(responseBody);
        int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
        if (results != null) {
            for (Map<String, Object> jsonResult : results) {
                String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
                String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
                String error = (String) jsonResult.get(JSON_ERROR);
                Result result = new Result.Builder().messageId(messageId)
                        .canonicalRegistrationId(canonicalRegId).errorCode(error).build();
                builder.addResult(result);
            }
        }
        MulticastResult multicastResult = builder.build();
        return multicastResult;
    } catch (ParseException e) {
        throw newIoException(responseBody, e);
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:com.cloudant.http.internal.interceptors.CookieInterceptor.java

@Override
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {

    // Check if this interceptor is valid before attempting any kind of renewal
    if (shouldAttemptCookieRequest.get()) {

        HttpURLConnection connection = context.connection.getConnection();

        // If we got a 401 or 403 we might need to renew the cookie
        try {//from  w  w  w.  j  a v  a 2s.  c om
            boolean renewCookie = false;
            int statusCode = connection.getResponseCode();

            if (statusCode == HttpURLConnection.HTTP_FORBIDDEN
                    || statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                InputStream errorStream = connection.getErrorStream();
                String errorString = null;
                if (errorStream != null) {
                    try {
                        // Get the string value of the error stream
                        errorString = IOUtils.toString(errorStream, "UTF-8");
                    } finally {
                        IOUtils.closeQuietly(errorStream);
                    }
                }
                logger.log(Level.FINE, String.format(Locale.ENGLISH, "Intercepted " + "response %d %s",
                        statusCode, errorString));
                switch (statusCode) {
                case HttpURLConnection.HTTP_FORBIDDEN: //403
                    // Check if it was an expiry case
                    // Check using a regex to avoid dependency on a JSON library.
                    // Note (?siu) flags used for . to also match line breaks and for
                    // unicode
                    // case insensitivity.
                    if (errorString != null && errorString
                            .matches("(?siu)" + ".*\\\"error\\\"\\s*:\\s*\\\"credentials_expired\\\".*")) {
                        // Was expired - set boolean to renew cookie
                        renewCookie = true;
                    } else {
                        // Wasn't a credentials expired, throw exception
                        HttpConnectionInterceptorException toThrow = new HttpConnectionInterceptorException(
                                errorString);
                        // Set the flag for deserialization
                        toThrow.deserialize = errorString != null;
                        throw toThrow;
                    }
                    break;
                case HttpURLConnection.HTTP_UNAUTHORIZED: //401
                    // We need to get a new cookie
                    renewCookie = true;
                    break;
                default:
                    break;
                }

                if (renewCookie) {
                    logger.finest("Cookie was invalid attempt to get new cookie.");
                    boolean success = requestCookie(context);
                    if (success) {
                        // New cookie obtained, replay the request
                        context.replayRequest = true;
                    } else {
                        // Didn't successfully renew, maybe creds are invalid
                        context.replayRequest = false; // Don't replay
                        shouldAttemptCookieRequest.set(false); // Set the flag to stop trying
                    }
                }
            } else {
                // Store any cookies provided on the response
                storeCookiesFromResponse(connection);
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error reading response code or body from request", e);
        }
    }
    return context;

}

From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java

@Test
public void formatWithIllegalCharset1() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=application/json;charset=abc");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.connect();/*ww w  .  j  ava 2  s .co  m*/

    assertEquals(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode(), connection.getResponseCode());

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("The $format option 'application/json;charset=abc' is not supported."));
}

From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java

@Test
public void formatWithWrongParams() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=application/json;abc=xyz");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.connect();//www.ja  v  a 2s .  co m

    assertEquals(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode(), connection.getResponseCode());

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("The $format option 'application/json;abc=xyz' is not supported."));
}

From source file:com.onesignal.OneSignalRestClient.java

private static void makeRequest(String url, String method, JSONObject jsonBody,
        ResponseHandler responseHandler) {
    HttpURLConnection con = null;
    int httpResponse = -1;
    String json = null;/*from   w  w w . ja va  2 s  .  c  o  m*/

    try {
        con = (HttpURLConnection) new URL(BASE_URL + url).openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(TIMEOUT);
        con.setReadTimeout(TIMEOUT);

        if (jsonBody != null)
            con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestMethod(method);

        if (jsonBody != null) {
            String strJsonBody = jsonBody.toString();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody);

            byte[] sendBytes = strJsonBody.getBytes("UTF-8");
            con.setFixedLengthStreamingMode(sendBytes.length);

            OutputStream outputStream = con.getOutputStream();
            outputStream.write(sendBytes);
        }

        httpResponse = con.getResponseCode();

        InputStream inputStream;
        Scanner scanner;
        if (httpResponse == HttpURLConnection.HTTP_OK) {
            inputStream = con.getInputStream();
            scanner = new Scanner(inputStream, "UTF-8");
            json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
            scanner.close();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json);

            if (responseHandler != null)
                responseHandler.onSuccess(json);
        } else {
            inputStream = con.getErrorStream();
            if (inputStream == null)
                inputStream = con.getInputStream();

            if (inputStream != null) {
                scanner = new Scanner(inputStream, "UTF-8");
                json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                scanner.close();
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json);
            } else
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN,
                        method + " HTTP Code: " + httpResponse + " No response body!");

            if (responseHandler != null)
                responseHandler.onFailure(httpResponse, json, null);
        }
    } catch (Throwable t) {
        if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException)
            OneSignal.Log(OneSignal.LOG_LEVEL.INFO,
                    "Could not send last request, device is offline. Throwable: " + t.getClass().getName());
        else
            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t);

        if (responseHandler != null)
            responseHandler.onFailure(httpResponse, null, t);
    } finally {
        if (con != null)
            con.disconnect();
    }
}