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:dlauncher.authorization.DefaultCredentialsManager.java

private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors)
        throws ProtocolException, IOException, AuthorizationException {
    JSONObject obj = null;//from  ww w .j  a  v a 2 s. c o m
    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.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 ww . j  a va  2 s  .c o  m*/
    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:com.edgenius.wiki.Shell.java

/**
 * Please note, this method doesn't reset current Shell.key. If this request failed, the original Shell.key value is still remained.
 * @return//w ww.ja  v  a  2  s . c o  m
 */
public static boolean requestInstanceShellKey() {
    try {
        log.info("Request shell key for current instance");

        //reset last keyValidator value  - will use new one.
        keyValidator = null;
        HttpURLConnection conn = (HttpURLConnection) new URL(
                getShellURL(Installation.INSTANCE_ID, null, null, false, null, false)).openConnection();
        //as instance key request is important, so we extends its timeout as original 2 times.
        conn.setConnectTimeout(timeout * 2);
        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);
        }
        String response = new String(writer.toByteArray());

        //see GShell project, ShellServlet response for instance
        //Here return is MD5 of key value....
        if (response.startsWith("KEY-VALIDATOR:")) {
            lock.lock();
            try {
                keyValidator = response.substring(14).trim();
                if (!keyValidCondition.await(timeout * 2, TimeUnit.MILLISECONDS)) {
                    log.error("Unable to get valid Shell request for key. Request Instance shell key failed.");
                    keyValidator = null;
                    return false;
                }

                //here, suppose shell key is already fill in.
                return !StringUtils.isEmpty(Shell.key);
            } finally {
                lock.unlock();
            }
        }
        //suspect current thread to wait until key valid
    } catch (IOException e) {
        log.error("Unable to connect shell for notification", e);
    } catch (Throwable e) {
        log.error("Notify shell failure", e);
    }

    return false;
}

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  w  ww .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.appsimobile.appsii.module.weather.WeatherLoadingService.java

private static boolean downloadFile(Context context, ImageDownloadHelper.PhotoInfo photoInfo, String woeid,
        int idx) {

    WeatherUtils weatherUtils = AppInjector.provideWeatherUtils();

    File cacheDir = weatherUtils.getWeatherPhotoCacheDir(context);
    String fileName = weatherUtils.createPhotoFileName(woeid, idx);
    File photoImage = new File(cacheDir, fileName);
    try {/*from w w  w. j  a  v  a 2s . co m*/
        URL url = new URL(photoInfo.url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(30000);
        InputStream in = new BufferedInputStream(connection.getInputStream());
        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(photoImage));

            int totalRead = 0;
            try {
                byte[] bytes = new byte[64 * 1024];
                int read;
                while ((read = in.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                    totalRead += read;
                }
                out.flush();
            } finally {
                out.close();
            }
            if (BuildConfig.DEBUG) {
                Log.d("WeatherLoadingService", "received " + totalRead + " bytes for: " + photoInfo.url);
            }
        } finally {
            in.close();
        }
        return true;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

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

private static Object getCoinValueBTC_BTER() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;/*from   w w  w .  ja va 2  s .  c  om*/
    String currency = CoinDefinition.cryptsyMarketCurrency;
    String url = "https://bittrex.com/api/v1.1/public/getticker?market=BTC-CANN";

    HttpURLConnection connection = null;
    try {
        // final String currencyCode = currencies[i];
        final URL URL_bter = new URL(url);
        connection = (HttpURLConnection) URL_bter.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connection.connect();

        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            Io.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            String result = head.getString("result");
            if (result.equals("true")) {

                Double averageTrade = head.getDouble("Bid");

                if (currency.equalsIgnoreCase("BTC"))
                    btcRate = averageTrade;
            }

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException x) {
                    // swallow
                }
            }
        }
        return btcRate;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    } finally {
        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:msearch.filmeSuchen.sender.MediathekSrf.java

public static boolean ping(String url) throws SRFException {

    url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {//  w  w w  .j  a v a2  s.c  o m
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(1000); //1000ms timeout for connect, read timeout to infinity
        connection.setReadTimeout(0);
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        if (responseCode > 399 && responseCode != HttpURLConnection.HTTP_NOT_FOUND) {

            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new SRFException("TEST");
            }
            //MSLog.debugMeldung("SRF: " + responseCode + " + responseCode " + "Url " + url);
            return false;
        }
        return (200 <= responseCode && responseCode <= 399);

    } catch (IOException exception) {
        return false;
    }
}

From source file:com.iStudy.Study.Renren.Util.java

private static HttpURLConnection sendFormdata(String reqUrl, Bundle parameters, String fileParamName,
        String filename, String contentType, byte[] data) {
    HttpURLConnection urlConn = null;
    try {//from ww w.  ja  va2  s  . com
        URL url = new URL(reqUrl);
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setConnectTimeout(5000);// ??jdk
        urlConn.setReadTimeout(5000);// ??jdk 1.5??,?
        urlConn.setDoOutput(true);

        urlConn.setRequestProperty("connection", "keep-alive");

        String boundary = "-----------------------------114975832116442893661388290519"; // 
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        boundary = "--" + boundary;
        StringBuffer params = new StringBuffer();
        if (parameters != null) {
            for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
                String name = iter.next();
                String value = parameters.getString(name);
                params.append(boundary + "\r\n");
                params.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
                // params.append(URLEncoder.encode(value, "UTF-8"));
                params.append(value);
                params.append("\r\n");
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(boundary);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + filename
                + "\"\r\n");
        sb.append("Content-Type: " + contentType + "\r\n\r\n");
        byte[] fileDiv = sb.toString().getBytes();
        byte[] endData = ("\r\n" + boundary + "--\r\n").getBytes();
        byte[] ps = params.toString().getBytes();

        OutputStream os = urlConn.getOutputStream();
        os.write(ps);
        os.write(fileDiv);
        os.write(data);
        os.write(endData);

        os.flush();
        os.close();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return urlConn;
}

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  ww . ja v a  2  s .  c  om*/
    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;
}

From source file:net.bible.service.common.CommonUtils.java

/** return true if URL is accessible
 * //  w w w  .  j a  v a2 s  .  com
 * Since Android 3 must do on different or NetworkOnMainThreadException is thrown
 */
public static boolean isHttpUrlAvailable(final String urlString) {
    boolean isAvailable = false;
    final int TIMEOUT_MILLIS = 3000;

    try {
        class CheckUrlThread extends Thread {
            public boolean checkUrlSuccess = false;

            public void run() {
                HttpURLConnection connection = null;
                try {
                    // might as well test for the url we need to access
                    URL url = new URL(urlString);

                    Log.d(TAG, "Opening test connection");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(TIMEOUT_MILLIS);
                    Log.d(TAG, "Connecting to test internet connection");
                    connection.connect();
                    checkUrlSuccess = (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
                    Log.d(TAG, "Url test result for:" + urlString + " is " + checkUrlSuccess);
                } catch (IOException e) {
                    Log.i(TAG, "No internet connection");
                    checkUrlSuccess = false;
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }
        ;

        CheckUrlThread checkThread = new CheckUrlThread();
        checkThread.start();
        checkThread.join(TIMEOUT_MILLIS);
        isAvailable = checkThread.checkUrlSuccess;
    } catch (InterruptedException e) {
        Log.e(TAG, "Interrupted waiting for url check to complete", e);
    }
    return isAvailable;
}