Example usage for javax.net.ssl HttpsURLConnection getErrorStream

List of usage examples for javax.net.ssl HttpsURLConnection getErrorStream

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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.google.android.apps.picview.request.CachedWebRequestFetcher.java

/** 
 * Fetches the given URL from the web./*  w ww  .  j a  v a 2 s .  c o m*/
 */
public String fetchFromWeb(URL url) {

    Log.d(TAG, "Fetching from web: " + url.toString());
    HttpsURLConnection conn = null;
    HttpResponse resp = null;
    try {
        conn = (HttpsURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setReadTimeout(30000); // 30 seconds. 
        conn.setDoInput(true);
        conn.addRequestProperty("GData-Version", "2");
        conn.connect();
        InputStream is = conn.getInputStream();
        return readStringFromStream(is);
    } catch (Exception e) {
        Log.v(TAG, readStringFromStream(conn.getErrorStream()));
        e.printStackTrace();
    }
    return null;
}

From source file:com.wso2telco.MePinStatusRequest.java

public String call() {
    String allowStatus = null;/* www .  j  a  v  a  2 s  .c om*/

    String clientId = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinClientId();
    String url = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinUrl();
    url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId + "";
    if (log.isDebugEnabled()) {
        log.info("MePIN Status URL : " + url);
    }
    String authHeader = "Basic " + configurationService.getDataHolder().getMobileConnectConfig()
            .getSessionUpdaterConfig().getMePinAccessToken();

    try {
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", authHeader);

        String resp = "";
        int statusCode = connection.getResponseCode();
        InputStream is;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String output;
        while ((output = br.readLine()) != null) {
            resp += output;
        }
        br.close();

        if (log.isDebugEnabled()) {
            log.debug("MePIN Status Response Code : " + statusCode + " " + connection.getResponseMessage());
            log.debug("MePIN Status Response : " + resp);
        }

        JsonObject responseJson = new JsonParser().parse(resp).getAsJsonObject();
        String respTransactionId = responseJson.getAsJsonPrimitive("transaction_id").getAsString();
        JsonPrimitive allowObject = responseJson.getAsJsonPrimitive("allow");

        if (allowObject != null) {
            allowStatus = allowObject.getAsString();
            if (Boolean.parseBoolean(allowStatus)) {
                allowStatus = "APPROVED";
                String sessionID = DatabaseUtils.getMePinSessionID(respTransactionId);
                DatabaseUtils.updateStatus(sessionID, allowStatus);
            }
        }

    } catch (IOException e) {
        log.error("Error while MePIN Status request" + e);
    } catch (SQLException e) {
        log.error("Error in connecting to DB" + e);
    }
    return allowStatus;
}

From source file:org.jboss.aerogear.adm.AdmService.java

/**
 * Request that ADM deliver your message to a specific instance of your app.
 *
 * @param registrationId representing the unique identifier of the device
 * @param clientId unique ID supplied by ADM Services
 * @param clientSecret secret value supplied by ADM services
 * @param payload , a String representing the complete payload to be submitted
 * @throws Exception if sending the message fails
 *//*from  ww  w  . j a v  a2 s .  co  m*/
public void sendMessageToDevice(final String registrationId, final String clientId, final String clientSecret,
        final String payload) throws Exception {

    if (accessToken == null) {
        accessToken = tokenService.getAuthToken(clientId, clientSecret);
    }

    // Generate the HTTPS connection for the POST request.
    // You cannot make a connection over plain HTTP.
    HttpsURLConnection conn = post(registrationId, payload);

    // Obtain the response code from the connection.
    final int responseCode = conn.getResponseCode();

    // Check if we received a failure response, and if so, get the reason for the failure.
    if (responseCode != 200) {
        if (responseCode == 401) {
            accessToken = tokenService.getAuthToken(clientId, clientSecret);
            sendMessageToDevice(registrationId, clientId, clientSecret, payload);
        } else {
            String errorContent = parseResponse(conn.getErrorStream());
            throw new RuntimeException(String.format("ERROR: The enqueue request failed with a "
                    + "%d response code, with the following message: %s", responseCode, errorContent));
        }

    } else {
        // The request was successful. The response contains the canonical Registration ID for the specific instance of your
        // app, which may be different that the one used for the request.

        final String responseContent = parseResponse(conn.getInputStream());
        final JSONObject parsedObject = new JSONObject(responseContent);

        final String canonicalRegistrationId = parsedObject.getString("registrationID");

        // Check if the two Registration IDs are different.
        if (!canonicalRegistrationId.equals(registrationId)) {
            // At this point the data structure that stores the Registration ID values should be updated
            // with the correct Registration ID for this particular app instance.
        }
    }

}

From source file:com.illusionaryone.GameWispAPI.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String methodType, String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    URL urlRaw;/*from  w  w w .j a  v a 2s.com*/
    HttpsURLConnection urlConn;
    String jsonText = "";

    if (sAccessToken.length() == 0) {
        if (!noAccessWarning) {
            com.gmt2001.Console.err.println(
                    "GameWispAPI: Attempting to use GameWisp API without key. Disable GameWisp module.");
            noAccessWarning = true;
        }
        JSONStringer jsonObject = new JSONStringer();
        return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject()
                .endObject().toString()));
    }

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod(methodType);
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");

        if (methodType.equals("POST")) {
            urlConn.setDoOutput(true);
            urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } else {
            urlConn.addRequestProperty("Content-Type", "application/json");
        }

        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GameWispAPI::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "...");
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(),
                        "");
                com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage());
            }
        }
    }

    return (jsonResult);
}

From source file:com.illusionaryone.GameWispAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String methodType, String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    URL urlRaw;//from  ww w  .jav  a  2 s .  c  o m
    HttpsURLConnection urlConn;
    String jsonText = "";

    if (sAccessToken.length() == 0) {
        if (!noAccessWarning) {
            com.gmt2001.Console.err.println(
                    "GameWispAPIv1: Attempting to use GameWisp API without key. Disabling the GameWisp module.");
            PhantomBot.instance().getDataStore().set("modules", "./handlers/gameWispHandler.js", "false");
            noAccessWarning = true;
        }
        JSONStringer jsonObject = new JSONStringer();
        return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject()
                .endObject().toString()));
    }

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod(methodType);
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (methodType.equals("POST")) {
            urlConn.setDoOutput(true);
            urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } else {
            urlConn.addRequestProperty("Content-Type", "application/json");
        }

        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GameWispAPIv1::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "...");
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(),
                        "");
                com.gmt2001.Console.err
                        .println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host.
 * /*  w ww. ja  v  a  2 s .  c  o m*/
 * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of
 * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just
 * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with
 * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since
 * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for
 * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear.
 * 
 * @param notary
 *            The notary to contact
 * @param hostPort
 *            The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private static String contactNotary(ConvergenceNotary notary, String hostPort)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)")
    String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29";

    // Build the url to connect to based on the Notary and the certificate's host
    URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+"));

    // Open a HttpsURLConnection for that url
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    /*
     * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according
     * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary.
     */
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,
            new TrustManager[] {
                    new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) },
            new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Set the timeout during which the Notary has to reply
    conn.setConnectTimeout(3000);

    // POST the fake fingerprint to the Notary
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream().
    InputStream is;
    if (conn.getResponseCode() >= 400) {
        is = conn.getErrorStream();

    } else {
        // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ...
        is = conn.getInputStream();
    }

    // Read the Notary's reply and store it
    String response = Message.inputStreamToString(is);

    // Close all opened streams
    wr.close();

    // Return the Notary's reply
    return response;

}

From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java

/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.//from   w  w w . ja  va2  s  .  c  om
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
    try {
        // Create the connection
        URL url = new URL(baseUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // Set parameters for the connection
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        // API now uses basic authentication
        String authString = login.getValue() + ":" + password.getValue();
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // Set the timeout so don't wait forever (unless timeout is set to 0)
        int timeoutMsec = timeout.getValue();
        con.setConnectTimeout(timeoutMsec);
        con.setReadTimeout(timeoutMsec);

        // Write the json data to the connection
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonStr);
        wr.flush();
        wr.close();

        // Get the response
        int responseCode = con.getResponseCode();

        // If wasn't successful then log the response so can debug
        if (responseCode != 200) {
            String responseStr = "";
            if (responseCode != 500) {
                // Response code indicates there was a problem so get the
                // reply in case API returned useful error message
                InputStream inputStream = con.getErrorStream();
                if (inputStream != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    responseStr = response.toString();
                }
            }

            // Lot that response code indicates there was a problem
            logger.error(
                    "Bad HTTP response {} when writing data to SFMTA "
                            + "API. Response text=\"{}\" URL={} json=\n{}",
                    responseCode, responseStr, baseUrl, jsonStr);
        }

        // Done so disconnect just for the heck of it
        con.disconnect();

        // Return whether was successful
        return responseCode == 200;
    } catch (IOException e) {
        logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(),
                baseUrl, jsonStr);

        // Return that was unsuccessful
        return false;
    }

}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private JSONObject getErrorMessage(HttpsURLConnection urlConnection) {
    JSONObject error_message = new JSONObject();
    if (urlConnection != null) {
        InputStream error_stream = urlConnection.getErrorStream();
        if (error_stream != null) {
            String error_response = new Scanner(error_stream).useDelimiter("\\A").next();
            try {
                error_message = new JSONObject(error_response);
            } catch (JSONException e) {
                e.printStackTrace();//from  ww w  .  j a v a 2s  . com
            }
            urlConnection.disconnect();
        }
    }
    return error_message;
}

From source file:com.gmt2001.TwitchAPIv2.java

private JSONObject GetData(request_type type, String url, String post, String oauth) {
    JSONObject j = new JSONObject();

    try {//from  w w w  . ja  v  a 2s  .c  o m
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);

        c.connect();

        if (!post.isEmpty()) {
            IOUtils.write(post, c.getOutputStream());
        }

        String content;

        if (c.getResponseCode() == 200) {
            content = IOUtils.toString(c.getInputStream(), c.getContentEncoding());
        } else {
            content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding());
        }

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
    }

    return j;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

@Override
public String execute(String request, int connectTimeout, int readTimeout) {
    // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection()
    // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be
    // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in
    // max 1 second.
    String response = null;/*from   w  w  w .  ja va2s .c  om*/
    HttpsURLConnection connection = null;
    try {
        String correctedRequest = checkSessionToken(request);
        connection = getConnection(correctedRequest, connectTimeout, readTimeout);
        if (connection != null) {
            connection.connect();
            final int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) {
                if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                    response = IOUtils.toString(connection.getErrorStream());
                } else {
                    response = IOUtils.toString(connection.getInputStream());
                }
                if (response != null) {
                    if (!response.contains("Authentication failed")) {
                        if (loginCounter > 0) {
                            connectionManager.checkConnection(responseCode);
                        }
                        loginCounter = 0;
                    } else {
                        connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM);
                        loginCounter++;
                    }
                }

            }
            connection.disconnect();
            if (response == null && connectionManager != null
                    && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) {
                if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                    execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()),
                            connectTimeout, readTimeout);
                    loginCounter++;
                } else {
                    connectionManager.checkConnection(responseCode);
                    loginCounter++;
                    return null;
                }
            }
            return response;
        }
    } catch (SocketTimeoutException e) {
        informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION);
    } catch (java.net.ConnectException e) {
        informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION);
    } catch (MalformedURLException e) {
        informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION);
    } catch (java.net.UnknownHostException e) {
        informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION);
    } catch (IOException e) {
        logger.error("An IOException occurred: ", e);
        if (connectionManager != null) {
            informConnectionManager(ConnectionManager.GENERAL_EXCEPTION);
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}