Example usage for java.net HttpURLConnection setConnectTimeout

List of usage examples for java.net HttpURLConnection setConnectTimeout

Introduction

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

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:com.magnet.plugin.common.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(CONNECTION_TIMEOUT);
                }/*from  w w w.j a  v  a2  s .co  m*/
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new Exception(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:de.schildbach.wallet.ExchangeRatesProvider.java

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

    HttpURLConnection connection = null;
    Reader reader = null;//from  ww  w .  j  ava  2s  . 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.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = 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 rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final Fiat rate = Fiat.parseFiat(currencyCode, rateStr);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new org.bitcoinj.utils.ExchangeRate(rate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

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

            return rates;
        } 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:itdelatrisu.opsu.Utils.java

/**
 * Returns a the contents of a URL as a string.
 * @param url the remote URL/*ww  w  .j  av  a2 s  . co  m*/
 * @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;
    }
}

From source file:com.chiorichan.util.WebUtils.java

/**
 * Opens an HTTP connection to a web URL and tests that the response is a valid 200-level code
 * and we can successfully open a stream to the content.
 * //from  w  w  w .  j a va2 s  . c o  m
 * @param url
 *            The HTTP URL indicating the location of the content.
 * @return True if the content can be accessed successfully, false otherwise.
 */
public static boolean pingHttpURL(String url) {
    InputStream stream = null;
    try {
        final HttpURLConnection conn = openHttpConnection(new URL(url));
        conn.setConnectTimeout(10000);

        int responseCode = conn.getResponseCode();
        int responseFamily = responseCode / 100;

        if (responseFamily == 2) {
            stream = conn.getInputStream();
            IOUtils.closeQuietly(stream);
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        return false;
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

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 ww  w . j  a v a  2 s .co 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:com.gmobi.poponews.util.HttpHelper.java

public static Response upload(String url, InputStream is) {
    Response response = new Response();
    String boundary = Long.toHexString(System.currentTimeMillis());
    HttpURLConnection connection = null;
    try {/*  ww  w.  j av a 2 s. c om*/
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        byte[] st = ("--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"data\"\r\n"
                + "Content-Type: application/octet-stream; charset=UTF-8\r\n"
                + "Content-Transfer-Encoding: binary\r\n\r\n").getBytes();
        byte[] en = ("\r\n--" + boundary + "--\r\n").getBytes();
        connection.setRequestProperty("Content-Length", String.valueOf(st.length + en.length + is.available()));
        OutputStream os = connection.getOutputStream();
        os.write(st);
        FileHelper.copy(is, os);
        os.write(en);
        os.flush();
        os.close();
        response.setStatusCode(connection.getResponseCode());
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
    }

    return response;
}

From source file:com.gmobi.poponews.util.HttpHelper.java

public static int download(String url, File file) {
    HttpURLConnection connection = null;
    int length = 0;
    try {/*from  w w  w . java  2s.c  o  m*/
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        length = connection.getContentLength();
        FileHelper.copy(connection.getInputStream(), file);
        connection = null;

    } catch (Exception e) {
        Logger.error(e);
    }
    return length;
}

From source file:com.gmobi.poponews.util.HttpHelper.java

private static Response doRequest(String url, Object raw, int method) {
    disableSslCheck();//from  ww w .ja v  a 2 s  . co  m
    boolean isJson = raw instanceof JSONObject;
    String body = raw == null ? null : raw.toString();
    Response response = new Response();
    HttpURLConnection connection = null;
    try {
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setUseCaches(false);
        if (method == HTTP_POST)
            connection.setRequestMethod("POST");
        if (body != null) {
            if (isJson) {
                connection.setRequestProperty("Accept", "application/json");
                connection.setRequestProperty("Content-Type", "application/json");
            }
            OutputStream os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            osw.write(body);
            osw.flush();
            osw.close();
        }
        InputStream in = connection.getInputStream();
        response.setBody(FileHelper.readText(in, "UTF-8"));
        response.setStatusCode(connection.getResponseCode());
        in.close();
        connection.disconnect();
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
        try {
            if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) {
                response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8"));
            }
        } catch (Exception ex) {
            Logger.error(ex);
        }
    }
    return response;
}

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 {//www. j  a  v  a2s .co  m
        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:org.immopoly.android.helper.WebHelper.java

public static JSONObject getHttpData(URL url, boolean signed, Context context) throws JSONException {
    JSONObject obj = null;//  w  w  w . j a  va2 s.  c  om
    if (Settings.isOnline(context)) {
        HttpURLConnection request;
        try {

            request = (HttpURLConnection) url.openConnection();

            request.addRequestProperty("User-Agent",
                    "immopoly android client " + ImmopolyActivity.getStaticVersionInfo());
            request.addRequestProperty("Accept-Encoding", "gzip");
            if (signed)
                OAuthData.getInstance(context).consumer.sign(request);
            request.setConnectTimeout(SOCKET_TIMEOUT);

            request.connect();
            String encoding = request.getContentEncoding();

            InputStream in;
            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                in = new GZIPInputStream(request.getInputStream());
            } else {
                in = new BufferedInputStream(request.getInputStream());
            }
            String s = readInputStream(in);
            JSONTokener tokener = new JSONTokener(s);
            obj = new JSONObject(tokener);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthMessageSignerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return obj;
}