Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:net.andylizi.colormotd.anim.utils.AttributionUtil.java

private static String sendGet(String url, String param, String charset) {
    StringBuilder result = new StringBuilder(1024);
    BufferedReader in = null;/*from   ww w . j a v a 2 s . c om*/
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("User-Agent", Main.getInstance().getDescription().getFullName());
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setUseCaches(true);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(3000);
        conn.connect();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        conn.disconnect();
    } catch (Exception e) {
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
        }
    }
    return result.toString();
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doGet(String endpoint, Map<String, String> headers) throws IOException {
    HttpResponse httpResponse;/*from  ww w .  j  av a2 s. c  om*/
    if (endpoint.startsWith("http://")) {
        URL url = new URL(endpoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setReadTimeout(30000);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                conn.setRequestProperty(key, headers.get(key));
            }
        }

        conn.connect();

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
            httpResponse.setResponseMessage(conn.getResponseMessage());

        } catch (IOException ignored) {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
            httpResponse.setResponseMessage(conn.getResponseMessage());
        } finally {
            if (rd != null) {
                rd.close();
            }
        }

        return httpResponse;
    }
    return null;
}

From source file:com.nhncorp.lucy.security.xss.listener.SecurityUtils.java

public static String getContentTypeFromUrlConnection(String strUrl, ContentTypeCacheRepo contentTypeCacheRepo) {
    // cache ?  ?.
    String result = contentTypeCacheRepo.getContentTypeFromCache(strUrl);
    //System.out.println("getContentTypeFromCache : " + result);
    if (StringUtils.isNotEmpty(result)) {
        return result;
    }/*from ww  w .  j a v a 2  s  .c o m*/

    HttpURLConnection con = null;

    try {
        URL url = new URL(strUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("HEAD");
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.connect();

        int resCode = con.getResponseCode();

        if (resCode != HttpURLConnection.HTTP_OK) {
            System.err.println("error");
        } else {
            result = con.getContentType();
            //System.out.println("content-type from response header: " + result);

            if (result != null) {
                contentTypeCacheRepo.addContentTypeToCache(strUrl, new ContentType(result, new Date()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }

    return result;

}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {//from   w w  w  .  j  a va2 s .co m
        Double btcRate = 0.0;

        Object result = getCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("https://blockchain.info/ticker");
        final HttpURLConnection connection = (HttpURLConnection) URL.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;

        Reader reader = null;
        try {
            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>();

            //Add Bitcoin information
            rates.put(CoinDefinition.cryptsyMarketCurrency,
                    new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                            Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")),
                            "pubapi.cryptsy.com"));

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                //final String rate = o.optString("15m", null);

                double rateForBTC = o.getDouble("15m") * btcRate;

                final String rate = String.format("%.8f", rateForBTC); //o.optString("15m", null);

                if (rate != null) {
                    try {
                        rates.put(currencyCode, new ExchangeRate(currencyCode,
                                Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
                    } catch (final ArithmeticException x) {
                        log.debug("problem reading exchange rate: " + currencyCode, x);
                    }
                }
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    }

    return null;
}

From source file:website.openeng.anki.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix,
        String method) {/*from   w w w .java  2 s  .co  m*/
    try {
        URL url = new URL(UrlToFile);

        String extension = UrlToFile.substring(UrlToFile.length() - 4);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(method);
        urlConnection.setRequestProperty("Referer", "website.openeng.anki");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(60000);
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, context.getCacheDir());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBitcoinCharts() {
    try {/*ww  w .  j  a va  2s. com*/
        Double btcRate = 0.0;

        Object result = getCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("http://api.bitcoincharts.com/v1/weighted_prices.json");
        final HttpURLConnection connection = (HttpURLConnection) URL.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;

        Reader reader = null;
        try {
            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>();

            //Add Bitcoin information
            rates.put(CoinDefinition.cryptsyMarketCurrency,
                    new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                            Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")),
                            "pubapi.cryptsy.com"));

            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);
                    String rate = o.optString("24h", null);
                    if (rate == null)
                        rate = o.optString("7d", null);
                    if (rate == null)
                        rate = o.optString("30d", null);

                    double rateForBTC = Double.parseDouble(rate);

                    rate = String.format("%.8f", rateForBTC * btcRate);

                    if (rate != null) {
                        try {
                            rates.put(currencyCode, new ExchangeRate(currencyCode,
                                    Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
                        } catch (final ArithmeticException x) {
                            log.debug("problem reading exchange rate: " + currencyCode, x);
                        }
                    }
                }
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    }

    return null;
}

From source file:crow.util.Util.java

public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException {
    int responseCode = -1;
    OutputStream osw = null;/*from  w  ww  .j a  v a2 s. com*/
    try {
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(12000);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        byte[] bytes = encodePostParam.getBytes("UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        osw = conn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("");
        } else {
            String s = inputStreamToString(conn.getInputStream());
            return s;
        }
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:Main.java

public static String[] getUrlInfos(String urlAsString, int timeout) {
    try {/*from ww  w  .j  a v a2  s  . c o  m*/
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent", "Mozilla/5.0 Gecko/20100915 Firefox/3.6.10");

        // on android we got problems because of this
        // so disable that for now
        //            hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        // default length of bufferedinputstream is 8k
        byte[] arr = new byte[K4];
        InputStream is = hConn.getInputStream();

        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        BufferedInputStream in = new BufferedInputStream(is, arr.length);
        in.read(arr);

        return getUrlInfosFromText(arr, hConn.getContentType());
    } catch (Exception ex) {
    }
    return new String[] { "", "" };
}

From source file:com.google.android.apps.muzei.util.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }//from w  w  w  .ja  v  a 2 s. c  o m

    String scheme = uri.getScheme();
    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);

        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:com.android.tools.idea.structure.MavenDependencyLookupDialog.java

@NotNull
private static List<String> searchMavenCentral(@NotNull String text) {
    try {/*  ww w. ja  va 2s .  c o m*/
        String url = String.format(MAVEN_CENTRAL_SEARCH_URL, RESULT_LIMIT, text);
        final HttpURLConnection urlConnection = HttpConfigurable.getInstance().openHttpConnection(url);
        urlConnection.setConnectTimeout(SEARCH_TIMEOUT);
        urlConnection.setReadTimeout(SEARCH_TIMEOUT);
        urlConnection.setRequestProperty("accept", "application/xml");

        InputStream inputStream = urlConnection.getInputStream();
        Document document;
        try {
            document = new SAXBuilder().build(inputStream);
        } finally {
            inputStream.close();
        }
        XPath idPath = XPath.newInstance("str[@name='id']");
        XPath versionPath = XPath.newInstance("str[@name='latestVersion']");
        List<Element> artifacts = (List<Element>) XPath.newInstance("/response/result/doc")
                .selectNodes(document);
        List<String> results = Lists.newArrayListWithExpectedSize(artifacts.size());
        for (Element element : artifacts) {
            try {
                String id = ((Element) idPath.selectSingleNode(element)).getValue();
                String version = ((Element) versionPath.selectSingleNode(element)).getValue();
                results.add(id + ":" + version);
            } catch (NullPointerException e) {
                // A result is missing an ID or version. Just skip it.
            }
        }
        return results;
    } catch (JDOMException e) {
        LOG.warn(e);
    } catch (IOException e) {
        LOG.warn(e);
    }
    return Collections.emptyList();
}