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:de.jdellay.wallet.ExchangeRatesProvider.java

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

    HttpURLConnection connection = null;
    Reader reader = null;//  w  w w .  j  a v  a2s  . 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.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, Constants.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 rate = o.optString(field, null);

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

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, source));
                                    break;
                                }
                            } catch (final ArithmeticException 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 {}", 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:dlauncher.authorization.DefaultCredentialsManager.java

private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors)
        throws ProtocolException, IOException, AuthorizationException {
    JSONObject obj = null;/*from w  w  w.ja  v a 2s . c  om*/
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(15 * 1000);
        con.setReadTimeout(15 * 1000);
        con.connect();
        try (OutputStream out = con.getOutputStream()) {
            out.write(post.toString().getBytes(Charset.forName("UTF-8")));
        }
        con.getResponseCode();
        InputStream instr;
        instr = con.getErrorStream();
        if (instr == null) {
            instr = con.getInputStream();
        }
        byte[] data = new byte[1024];
        int length;
        try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) {
            try (InputStream in = new BufferedInputStream(instr)) {
                while ((length = in.read(data)) >= 0) {
                    bytes.write(data, 0, length);
                }
            }
            byte[] rawBytes = bytes.toByteArray();
            if (rawBytes.length != 0) {
                obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8")));
            } else {
                obj = new JSONObject();
            }
            if (!ignoreErrors && obj.has("error")) {
                String error = obj.getString("error");
                String errorMessage = obj.getString("errorMessage");
                String cause = obj.optString("cause", null);
                if ("ForbiddenOperationException".equals(error)) {
                    if ("UserMigratedException".equals(cause)) {
                        throw new UserMigratedException(errorMessage);
                    }
                    throw new ForbiddenOperationException(errorMessage);
                }
                throw new AuthorizationException(
                        error + (cause != null ? "." + cause : "") + ": " + errorMessage);
            }
            return obj;
        }
    } catch (JSONException ex) {
        throw new InvalidResponseException(ex, obj);
    }
}

From source file:com.cloud.utils.UriUtils.java

public static Long getRemoteSize(String url) {
    Long remoteSize = (long) 0;
    HttpURLConnection httpConn = null;
    HttpsURLConnection httpsConn = null;
    try {/*from   w w  w. java  2s.  c  o m*/
        URI uri = new URI(url);
        if (uri.getScheme().equalsIgnoreCase("http")) {
            httpConn = (HttpURLConnection) uri.toURL().openConnection();
            if (httpConn != null) {
                httpConn.setConnectTimeout(2000);
                httpConn.setReadTimeout(5000);
                String contentLength = httpConn.getHeaderField("content-length");
                if (contentLength != null) {
                    remoteSize = Long.parseLong(contentLength);
                }
                httpConn.disconnect();
            }
        } else if (uri.getScheme().equalsIgnoreCase("https")) {
            httpsConn = (HttpsURLConnection) uri.toURL().openConnection();
            if (httpsConn != null) {
                String contentLength = httpsConn.getHeaderField("content-length");
                if (contentLength != null) {
                    remoteSize = Long.parseLong(contentLength);
                }
                httpsConn.disconnect();
            }
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URL " + url);
    } catch (IOException e) {
        throw new IllegalArgumentException("Unable to establish connection with URL " + url);
    }
    return remoteSize;
}

From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java

private static HttpURLConnection openConnection(final String strURL) throws IOException {
    final URL url = new URL(strURL);

    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    setConnectionUserAgent(conn);//from   w  w w  .j  a  v a  2 s . c o  m

    //Set a reasonable timeout.
    //Otherwise there is not timeout so we might never know if it fails,
    //so never have the chance to try again.
    conn.setConnectTimeout(HttpUtils.TIMEOUT_MILLIS);
    conn.setReadTimeout(HttpUtils.TIMEOUT_MILLIS);

    return conn;
}

From source file:com.spoiledmilk.ibikecph.util.HttpUtils.java

public static JsonResult readLink(String url_string, String method) {
    JsonResult result = new JsonResult();
    if (url_string == null) {
        return result;
    }//w w  w . j a  v a2  s . c  om
    URL url = null;
    HttpURLConnection httpget = null;
    try {
        LOG.d("HttpUtils readlink() " + url_string);
        url = new URL(url_string);
        httpget = (HttpURLConnection) url.openConnection();
        httpget.setDoInput(true);
        httpget.setRequestMethod(method);
        httpget.setRequestProperty("Accept", "application/json");
        httpget.setRequestProperty("Content-type", "application/json");
        httpget.setConnectTimeout(CONNECTON_TIMEOUT);
        httpget.setReadTimeout(CONNECTON_TIMEOUT);
        JsonNode root = null;
        root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class);
        if (root != null) {
            result.setNode(root);
        }
    } catch (JsonParseException e) {
        LOG.w("HttpUtils readLink() JsonParseException ", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (MalformedURLException e) {
        LOG.w("HttpUtils readLink() MalformedURLException", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (FileNotFoundException e) {
        LOG.w("HttpUtils readLink() FileNotFoundException", e);
        result.error = JsonResult.ErrorCode.NotFound;
    } catch (IOException e) {
        LOG.w("HttpUtils readLink() IOException", e);
        result.error = JsonResult.ErrorCode.ConnectionError;
    } finally {
        if (httpget != null) {
            httpget.disconnect();
        }
    }
    LOG.d("HttpUtils readLink() "
            + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed"));
    return result;
}

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

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

    HttpURLConnection connection = null;
    Reader reader = null;//from   ww  w  .  ja v  a  2 s  .  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.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 rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                final double btcRate = Double
                                        .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString());
                                DecimalFormat df = new DecimalFormat("#.########");
                                df.setRoundingMode(RoundingMode.HALF_UP);
                                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
                                dfs.setDecimalSeparator('.');
                                dfs.setGroupingSeparator(',');
                                df.setDecimalFormatSymbols(dfs);
                                final Fiat dogeRate = Fiat.parseFiat(currencyCode,
                                        df.format(btcRate * dogeBtcConversion));

                                if (dogeRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), 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: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");
}

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

public static boolean isUrlAccessible(String url) throws IOException {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setRequestMethod("HEAD");
    con.setReadTimeout(Constants.connection_read_timeout_ms);
    try {/*from   ww w  .j  a v a 2  s .  co  m*/
        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }
    } catch (IOException ex) {
        return false;
    }
    return true;
}

From source file:com.zzl.zl_app.cache.Utility.java

public static String uploadFile(File file, String RequestURL, String fileName) {
    Tools.log("IO", "RequestURL:" + RequestURL);
    String result = null;//from w w w . j ava2s.  c  om
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT);
        conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Charset", CHARSET); // ?
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            Tools.log("FileSize", "file:" + file.length());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
                Tools.log("FileSize", "size:" + len);
            }

            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            dos.close();
            is.close();
            /**
             * ??? 200=? ?????
             */
            int res = conn.getResponseCode();
            Tools.log("IO", "ResponseCode:" + res);
            if (res == 200) {
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
            }

        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    String rs = null;/*  w  w  w. j  a  va 2s  . c o m*/
    try {
        StringBuffer sb = new StringBuffer();
        if (method == null || method.equals("GET")) {
            strUrl = strUrl + "?" + urlencode(params);
        }
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        if (method == null || method.equals("GET")) {
            conn.setRequestMethod("GET");
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }
        conn.setRequestProperty("User-agent", userAgent);
        conn.setUseCaches(false);
        conn.setConnectTimeout(DEF_CONN_TIMEOUT);
        conn.setReadTimeout(DEF_READ_TIMEOUT);
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        if (params != null && method.equals("POST")) {
            try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                out.writeBytes(urlencode(params));
            }
        }
        InputStream is = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sb.append(strRead);
        }
        rs = sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
    return rs;
}