Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

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

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:ee.ria.xroad.proxy.ProxyMain.java

private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() {
    Map<String, DiagnosticsStatus> statuses = new HashMap<>();

    for (String tspUrl : ServerConf.getTspUrl()) {
        try {/*from ww  w .  j  a  v a  2  s  . c om*/
            URL url = new URL(tspUrl);

            log.info("Checking timestamp server status for url {}", url);

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS);
            con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "application/timestamp-query");
            con.connect();

            log.info("Checking timestamp server con {}", con);

            if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok",
                        con.getResponseCode(), con.getResponseMessage());
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            } else {
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            }

        } catch (Exception e) {
            log.warn("Timestamp status check failed {}", e);

            statuses.put(tspUrl,
                    new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl));
        }
    }
    return statuses;

}

From source file:com.dopecoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float leafBtcConversion,
        final String userAgent, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from  w w  w. j  av  a  2s. c o  m

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion))
                                        .toBigInteger();

                                if (leafRate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, leafRate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:Main.java

private static int safelyConnect(HttpURLConnection connection) throws IOException {
    try {/*from   w  w  w  .java 2 s  .c  om*/
        connection.connect();
    } catch (NullPointerException e) {
        // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
        throw new IOException(e);
    } catch (IllegalArgumentException e) {
        // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
        throw new IOException(e);
    } catch (IndexOutOfBoundsException e) {
        // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
        throw new IOException(e);
    } catch (SecurityException e) {
        // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
        throw new IOException(e);
    }
    try {
        return connection.getResponseCode();
    } catch (NullPointerException e) {
        // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
        throw new IOException(e);
    } catch (StringIndexOutOfBoundsException e) {
        // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
        throw new IOException(e);
    } catch (IllegalArgumentException e) {
        // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
        throw new IOException(e);
    }
}

From source file:com.edgenius.wiki.Shell.java

public static String requestSpaceThemeName(String spaceUname) {
    try {/*from   w  w w.j  a  va 2 s . co  m*/
        log.info("Request shell theme for space {}", spaceUname);

        //reset last keyValidator value  - will use new one.
        HttpURLConnection conn = (HttpURLConnection) new URL(getThemeRequestURL(spaceUname)).openConnection();
        conn.setConnectTimeout(timeout);
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        int len;
        byte[] bytes = new byte[200];
        while ((len = is.read(bytes)) != -1) {
            writer.write(bytes, 0, len);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return new String(writer.toByteArray());
        }
    } catch (IOException e) {
        log.error("Unable to connect shell for theme name request", e);
    } catch (Throwable e) {
        log.error("Notify shell failure", e);
    }

    return null;
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Gets the OAuth access token.//from  www  .j  a v  a 2 s  .  c o  m
 * @param clientId The Client key.
 * @param clientSecret The Client Secret
 */
public static String getToken(final String clientId, final String clientSecret) throws Exception {
    final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com"
            + "&client_id=" + URLEncoder.encode(clientId, ENCODING) + "&client_secret="
            + URLEncoder.encode(clientSecret, ENCODING);

    final URL url = new URL(DatamarketAccessUri);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
    wr.write(params);
    wr.flush();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - the name of the file, as saved to the repo (including extension)
 * @param backupLink - the link of the location to backup to if the repo copy isn't found
 * @return - the direct static link or the backup link if the file isn't found
 *///from   w w w  . j av a 2s  .co m
public static String getStaticCreeperhostLinkOrBackup(String file, String backupLink) {
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/FTB2/static/" + file;
    HttpURLConnection connection = null;
    boolean good = false;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        if (connection.getResponseCode() != 200) {
            for (String server : downloadServers.values()) {
                if (connection.getResponseCode() != 200) {
                    resolved = "http://" + server + "/FTB2/static/" + file;
                    connection = (HttpURLConnection) new URL(resolved).openConnection();
                    connection.setRequestProperty("Cache-Control", "no-transform");
                    connection.setRequestMethod("HEAD");
                } else {
                    if (connection.getResponseCode() == 200)
                        good = true;
                    break;
                }
            }
        } else if (connection.getResponseCode() == 200) {
            good = true;
        }
    } catch (IOException e) {
    }
    connection.disconnect();
    if (good)
        return resolved;
    else {
        Logger.logWarn("Using backupLink for " + file);
        return backupLink;
    }
}

From source file:org.apache.brooklyn.util.http.HttpTool.java

public static String getErrorContent(String url) {
    try {//w ww .ja  v  a 2 s. c  o m
        HttpURLConnection connection = (HttpURLConnection) connectToUrl(url);
        long startTime = System.currentTimeMillis();

        String err;
        int status;
        try {
            InputStream errStream = connection.getErrorStream();
            err = Streams.readFullyString(errStream);
            status = connection.getResponseCode();
        } finally {
            closeQuietly(connection);
        }

        if (LOG.isDebugEnabled())
            LOG.debug("read of err {} ({}ms) complete; http code {}", new Object[] { url,
                    Time.makeTimeStringRounded(System.currentTimeMillis() - startTime), status });
        return err;

    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}

From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java

private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project,
        boolean setProjectDir) {

    URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir);
    if (url == null) {
        return null;
    }/*w  ww.j av a2s.com*/
    HttpURLConnection httpConnection = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(50);
        httpConnection.setReadTimeout(1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);
        httpConnection.setRequestProperty("Content-Type", "application/json");
        httpConnection.connect();
        try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) {
            final String jsonRequest = new Gson().toJson(request);
            writer.write(jsonRequest);
            writer.flush();
            writer.close();
        }
        if (httpConnection.getResponseCode() == 200) {
            if (responseClass == null) {
                return null;
            }
            try (InputStream inputStream = httpConnection.getInputStream()) {
                String jsonResponse = IOUtils.toString(inputStream, "UTF-8");
                R response = new Gson().fromJson(jsonResponse, responseClass);
                return response;
            }
        } else {
            log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode()
                    + ": " + httpConnection.getResponseMessage());
        }
    } catch (IOException e) {
        log.warn("Unable to connect to dev server", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
    return null;
}

From source file:net.cbtltd.server.WebService.java

/**
 * Gets the connection to the JSON server.
 *
 * @param url the connection URL./* ww w .j  ava  2s .  c  o m*/
 * @param rq the request object.
 * @return the JSON string returned by the message.
 * @throws Throwable the exception thrown by the method.
 */
private static final String getConnection(URL url, String rq) throws Throwable {
    String jsonString = "";
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        //connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        if (rq != null) {
            connection.setRequestProperty("Accept", "application/json");
            connection.connect();
            byte[] outputBytes = rq.getBytes("UTF-8");
            OutputStream os = connection.getOutputStream();
            os.write(outputBytes);
        }

        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("HTTP:" + connection.getResponseCode() + "URL " + url);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        String line;
        while ((line = br.readLine()) != null) {
            jsonString += line;
        }
    } catch (Throwable x) {
        throw new RuntimeException(x.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return jsonString;
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static int sendGet(String sitePath) throws IOException {
    URL url = new URL(sitePath);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setReadTimeout(Constants.connection_read_timeout_ms);
    return con.getResponseCode();
    //con.setRequestProperty("User-Agent", "AzureTools for Intellij");
}