Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:de.darkblue.bongloader2.utils.ToolBox.java

/**
 * returns the file size using the config to retrieve the current version of
 * bongloader and setting the right user-agent
 *
 * @param config//from w  ww . j a  v  a  2  s  . co m
 * @param url
 * @return
 * @throws IOException
 */
public static long getFileSize(final Configuration config, final URL url) throws IOException {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        if (config != null) {
            connection.setRequestProperty("User-Agent", "BongLoader2 " + config.get(ConfigurationKey.VERSION));
        }
        connection.setConnectTimeout(2000);
        connection.connect();

        final String headerField = connection.getHeaderField("Content-Length");
        if (headerField == null) {
            throw new IOException("Did not get a content length for the connection to " + url);
        }

        final String rawContentLength = headerField.trim();
        return Long.valueOf(rawContentLength);
        //return connection.getContentLength();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:edu.stanford.muse.launcher.Main.java

private static boolean killRunningServer(String url) throws IOException {
    try {/*from  w  w w  . ja  v a  2 s. c  o m*/
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false
        String http = url
                + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20Muse"; // version num spaces and brackets screw up the URL connection
        System.err.println("Sending a kill request to " + http);
        HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection();
        u.connect();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:com.rimbit.android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

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

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        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) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

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

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

    return null;

}

From source file:edu.stanford.epadd.launcher.Main.java

private static boolean killRunningServer(String url) throws IOException {
    try {//from www  .  j  av a 2  s  .c o m
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false
        String http = url
                + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection
        System.err.println("Sending a kill request to " + http);
        HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection();
        u.connect();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

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   w  ww  .j a v  a  2 s . co m*/
            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.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;/*  w w  w  .j a  va  2s  .  co  m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        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) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

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

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

    return null;

}

From source file:com.matthewmitchell.nubits_android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;//ww  w  .  j  a v  a 2  s .c om

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        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) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } else {
            log.warn("http status {} when fetching exchange rates from {}", 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:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

public static String downloadFileAsString(String url) {
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {//  w ww .  j a  va 2s. c om
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = bufferedReader.readLine()) != null)
                stringBuilder.append(line);

            bufferedReader.close();

            return stringBuilder.toString();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}

From source file:com.example.igorklimov.popularmoviesdemo.helpers.Utility.java

public static String getJsonResponse(String s) {
    HttpURLConnection connection = null;
    InputStream input = null;//  w w  w .j a v  a  2s  .  c  o m
    BufferedReader reader = null;
    String JsonResponse = null;

    try {
        URL url = new URL(s);
        Log.d("TAG", url.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        input = connection.getInputStream();
        StringBuilder builder = new StringBuilder();

        if (input != null) {
            reader = new BufferedReader(new InputStreamReader(input));
            String line;

            while ((line = reader.readLine()) != null) {
                builder.append(line).append("\n");
            }
            JsonResponse = builder.toString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return JsonResponse;
}

From source file:itdelatrisu.opsu.Utils.java

/**
 * Returns a the contents of a URL as a string.
 * @param url the remote URL//from w  ww  . j  ava  2 s .com
 * @return the contents as a string, or null if any error occurred
 * @author Roland Illig (http://stackoverflow.com/a/4308662)
 * @throws IOException if an I/O exception occurs
 */
public static String readDataFromUrl(URL url) throws IOException {
    // open connection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(Download.CONNECTION_TIMEOUT);
    conn.setReadTimeout(Download.READ_TIMEOUT);
    conn.setUseCaches(false);
    try {
        conn.connect();
    } catch (SocketTimeoutException e) {
        Log.warn("Connection to server timed out.", e);
        throw e;
    }

    if (Thread.interrupted())
        return null;

    // read contents
    try (InputStream in = conn.getInputStream()) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = rd.read()) != -1)
            sb.append((char) c);
        return sb.toString();
    } catch (SocketTimeoutException e) {
        Log.warn("Connection to server timed out.", e);
        throw e;
    }
}