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:de.thwildau.gcm.google.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, String, int)} for more info.
 *
 * @return result of the post, or {@literal null} if the GCM service was
 *         unavailable.// w ww.  ja  v  a  2 s  .  co  m
 *
 * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status.
 * @throws IllegalArgumentException if registrationId is {@literal null}.
 */
public Result sendNoRetry(Message message, String registrationId) throws IOException {
    StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
    Boolean delayWhileIdle = message.isDelayWhileIdle();
    if (delayWhileIdle != null) {
        addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
    }
    String collapseKey = message.getCollapseKey();
    if (collapseKey != null) {
        addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
    }
    Integer timeToLive = message.getTimeToLive();
    if (timeToLive != null) {
        addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
    }
    for (Entry<String, String> entry : message.getData().entrySet()) {
        String key = PARAM_PAYLOAD_PREFIX + entry.getKey();
        String value = entry.getValue();
        addParameter(body, key, URLEncoder.encode(value, UTF8));
    }
    String requestBody = body.toString();
    logger.finest("Request body: " + requestBody);
    HttpURLConnection conn = post(GCM_SEND_ENDPOINT, requestBody);
    int status = conn.getResponseCode();
    if (status == 503) {
        logger.fine("GCM service is unavailable");
        return null;
    }
    if (status != 200) {
        String responseBody = getString(conn.getErrorStream());
        logger.finest("Plain post error response: " + responseBody);
        throw new InvalidRequestException(status, responseBody);
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        try {
            String line = reader.readLine();

            if (line == null || line.equals("")) {
                throw new IOException("Received empty response from GCM service.");
            }
            String[] responseParts = split(line);
            String token = responseParts[0];
            String value = responseParts[1];
            if (token.equals(TOKEN_MESSAGE_ID)) {
                Builder builder = new Result.Builder().messageId(value);
                // check for canonical registration id
                line = reader.readLine();
                if (line != null) {
                    responseParts = split(line);
                    token = responseParts[0];
                    value = responseParts[1];
                    if (token.equals(TOKEN_CANONICAL_REG_ID)) {
                        builder.canonicalRegistrationId(value);
                    } else {
                        logger.warning("Received invalid second line from GCM: " + line);
                    }
                }

                Result result = builder.build();
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("Message created succesfully (" + result + ")");
                }
                return result;
            } else if (token.equals(TOKEN_ERROR)) {
                return new Result.Builder().errorCode(value).build();
            } else {
                throw new IOException("Received invalid response from GCM: " + line);
            }
        } finally {
            reader.close();
        }
    } finally {
        conn.disconnect();
    }
}

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

@Test
public void invalidAcceptHeader1() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT, "abc");
    connection.connect();//w  ww  .  j  av a2s.co  m

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

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content
            .contains("The content-type range ' abc' is not supported as " + "value of the Accept header."));
}

From source file:io.confluent.kafkarest.tools.ProducerPerformance.java

@Override
protected void doIteration(PerformanceStats.Callback cb) {
    HttpURLConnection connection = null;
    try {//from w  ww .j  a  v  a 2s  .  c o  m
        URL url = new URL(targetUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT);
        connection.setRequestProperty("Content-Length", requestEntityLength);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        OutputStream os = connection.getOutputStream();
        os.write(requestEntity);
        os.flush();
        os.close();

        int responseStatus = connection.getResponseCode();
        if (responseStatus >= 400) {
            InputStream es = connection.getErrorStream();
            ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class);
            es.close();
            throw new RuntimeException(String.format("Unexpected HTTP error status %d: %s", responseStatus,
                    errorMessage.getMessage()));
        }
        InputStream is = connection.getInputStream();
        while (is.read(buffer) > 0) {
            // Ignore output, just make sure we actually receive it
        }
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    cb.onCompletion(recordsPerIteration, bytesPerIteration);
}

From source file:org.compose.mobilesdk.android.ServerRequestTask.java

public String doPUTRequest(URL requestUrl) {
    String responseString = null;

    try {/*from   ww w  . j  a  v  a  2s .  c o m*/
        HttpURLConnection httpCon = (HttpURLConnection) requestUrl.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setRequestProperty("Content-Type", "application/json");
        httpCon.setRequestProperty("Authorization", header_parameters);
        httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        httpCon.setRequestProperty("Accept", "*/*");

        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write("" + this.message);
        out.close();

        if (DEBUG) {
            BufferedReader in = null;
            if (httpCon.getErrorStream() != null)
                in = new BufferedReader(new InputStreamReader(httpCon.getErrorStream()));
            else
                in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {

                Log.i(DEBUG_INFO, inputLine);
            }
            in.close();

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return responseString;
}

From source file:eu.codeplumbers.cosi.services.CosiNoteService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiNoteService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // delete all local notes
    new Delete().from(Note.class).execute();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/request/note/cosiall/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();/* w  w  w.  j  a  v a 2 s  .c o m*/

    if (isNetworkAvailable()) {
        try {
            URL urlO = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // read the response
            int status = conn.getResponseCode();
            InputStream in = null;

            if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                in = conn.getErrorStream();
            } else {
                in = conn.getInputStream();
            }

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONArray jsonArray = new JSONArray(result);

            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Note note = Note.getByRemoteId(noteJson.get("_id").toString());

                    if (note == null) {
                        note = new Note(noteJson);
                    } else {
                        boolean versionIncremented = note.getVersion() < Integer
                                .valueOf(noteJson.getString("version"));

                        int modifiedOnServer = DateUtils.compareDateStrings(
                                Long.valueOf(note.getLastModificationValueOf()),
                                noteJson.getLong("lastModificationValueOf"));

                        if (versionIncremented || modifiedOnServer == -1) {
                            note.setTitle(noteJson.getString("title"));
                            note.setContent(noteJson.getString("content"));
                            note.setCreationDate(noteJson.getString("creationDate"));
                            note.setLastModificationDate(noteJson.getString("lastModificationDate"));
                            note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf"));
                            note.setParentId(noteJson.getString("parent_id"));
                            // TODO: 10/3/16
                            // handle note paths
                            note.setPath(noteJson.getString("path"));
                            note.setVersion(Integer.valueOf(version));
                        }

                    }

                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mBuilder.setContentText("Getting note : " + note.getTitle());
                    mNotifyManager.notify(notification_id, mBuilder.build());

                    EventBus.getDefault()
                            .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle()));
                    note.save();
                }
            } else {
                EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            }

            in.close();
            conn.disconnect();

            mNotifyManager.cancel(notification_id);
            EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK"));
        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

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

@Test
public void validFormatWithIncorrectAcceptCharsetHeader() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf<8");
    connection.connect();//from   w  ww .j  ava2s.  c o m

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

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("The Accept charset header 'utf<8' is not supported."));
}

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

@Test
public void invalidAcceptCharsetHeader2() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "abc");
    connection.connect();//from   www.  j  a v  a 2  s.  c o  m

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

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("The charset specified in Accept charset header 'abc' is not supported."));
}

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

@Test
public void validFormatWithIllegalAcceptCharsetHeader() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "abc");
    connection.connect();/*w w w . j  a v a  2s.  c om*/

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

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("The charset specified in Accept charset " + "header 'abc' is not supported."));
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///ww w  . j  ava  2 s .  co  m
public String getRemoteLoyaltyCards() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

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

@Test
public void validFormatWithIncorrectQParamInAcceptCharsetHeader() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=<");
    connection.connect();//from  w  w  w.jav  a2  s.com

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

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("The Accept charset header 'utf-8;q=<' is not supported."));
}