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.wx.kernel.util.HttpKit.java

private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    URL _url = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
    }/*  w ww .  ja  v a2s.c  o m*/

    conn.setRequestMethod(method);
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setConnectTimeout(19000);
    conn.setReadTimeout(19000);

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if (headers != null && !headers.isEmpty())
        for (Entry<String, String> entry : headers.entrySet())
            conn.setRequestProperty(entry.getKey(), entry.getValue());

    return conn;
}

From source file:com.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? //from w w  w . ja va  2s . c o m
 * 
 * @return
 */
@Deprecated
public static String downMedia(String access_token, String msgType, String media_id, String path) {
    String localFile = null;
    //      SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/");
    try {
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token
                + "&media_id=" + media_id;
        // log.error(path);
        // ? ?
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        String xx = conn.getHeaderField("Content-disposition");
        try {
            log.debug("===? +==?==" + xx);
            if (xx == null) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                String result = null;
                while ((line = reader.readLine()) != null) {
                    if (result == null) {
                        result = line;
                    } else {
                        result += line;
                    }
                }
                System.out.println(result);
                JSONObject dataJson = JSONObject.parseObject(result);
                return dataJson.getString("errcode");
            }
        } catch (Exception e) {
        }
        if (conn.getResponseCode() == 200) {
            String Content_disposition = conn.getHeaderField("Content-disposition");
            InputStream inputStream = conn.getInputStream();
            // // ?
            // Long fileSize = conn.getContentLengthLong();
            //  +
            String savePath = path + "/" + msgType;
            // ??
            String fileName = StringUtil.getDateSimpleStr()
                    + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", "");
            // 
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            // ??
            if (!saveDirFile.canWrite()) {
                log.error("??");
                throw new Exception();
            }
            // System.out.println("------------------------------------------------");
            // ?
            File file = new File(saveDirFile + "/" + fileName);
            FileOutputStream outStream = new FileOutputStream(file);
            int len = -1;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outStream.write(b, 0, len);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
            // ?
            localFile = fileName;
        }
    } catch (Exception e) {
        log.error("? !", e);
    } finally {

    }
    return localFile;
}

From source file:net.drgnome.virtualpack.util.Util.java

public static boolean hasUpdate(int projectID, String version) {
        try {/*from  ww  w.  j a  va  2 s . c om*/
            HttpURLConnection con = (HttpURLConnection) (new URL(
                    "https://api.curseforge.com/servermods/files?projectIds=" + projectID)).openConnection();
            con.setConnectTimeout(5000);
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
            con.setRequestProperty("Pragma", "no-cache");
            con.connect();
            JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream()));
            String[] cdigits = ((String) ((JSONObject) json.get(json.size() - 1)).get("name")).toLowerCase()
                    .split("\\.");
            String[] vdigits = version.toLowerCase().split("\\.");
            int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length;
            int a;
            int b;
            for (int i = 0; i < max; i++) {
                a = b = 0;
                try {
                    a = Integer.parseInt(cdigits[i]);
                } catch (Exception e1) {
                    char[] c = cdigits[i].toCharArray();
                    for (int j = 0; j < c.length; j++) {
                        a += (c[j] << ((c.length - (j + 1)) * 8));
                    }
                }
                try {
                    b = Integer.parseInt(vdigits[i]);
                } catch (Exception e1) {
                    char[] c = vdigits[i].toCharArray();
                    for (int j = 0; j < c.length; j++) {
                        b += (c[j] << ((c.length - (j + 1)) * 8));
                    }
                }
                if (a > b) {
                    return true;
                } else if (a < b) {
                    return false;
                } else if ((i == max - 1) && (cdigits.length > vdigits.length)) {
                    return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

From source file:com.sunchenbin.store.feilong.core.net.URLConnectionUtil.java

/**
 * Prepare connection.//from w  ww. j a  v  a2s . com
 *
 * @param httpURLConnection
 *            the http url connection
 * @param httpRequest
 *            the http request
 * @param useConnectionConfig
 *            the use connection config
 * @throws IOException
 *             the IO exception
 * @since 1.4.0
 * @see "org.springframework.http.client.SimpleClientHttpRequestFactory#prepareConnection(HttpURLConnection, String)"
 */
private static void prepareConnection(HttpURLConnection httpURLConnection, HttpRequest httpRequest,
        ConnectionConfig useConnectionConfig) throws IOException {
    HttpMethodType httpMethodType = httpRequest.getHttpMethodType();

    // ?HttpUrlConnectionconnectTimeout
    httpURLConnection.setConnectTimeout(useConnectionConfig.getConnectTimeout());
    httpURLConnection.setReadTimeout(useConnectionConfig.getReadTimeout());

    httpURLConnection.setRequestMethod(httpMethodType.getMethod().toUpperCase());//?,?  java.net.ProtocolException: Invalid HTTP method: get

    httpURLConnection.setDoOutput(HttpMethodType.POST == httpMethodType);

    Map<String, String> headerMap = httpRequest.getHeaderMap();
    if (null != headerMap) {
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

public static InputStream getResource(String imageUrl) throws IOException {
    HttpURLConnection httpUrlConnection = null;

    URL url = new URL(imageUrl);
    httpUrlConnection = (HttpURLConnection) url.openConnection();
    HttpHelpers.addCommonHeaders(httpUrlConnection);
    httpUrlConnection.setConnectTimeout(NETWORK_TIMEOUT);
    httpUrlConnection.setReadTimeout(NETWORK_TIMEOUT);
    httpUrlConnection.connect();//from  ww  w  .  j a  v  a 2s  . c om
    return getInputStream(httpUrlConnection);

}

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;/* www .  j  a va 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.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:com.wisdombud.right.client.common.HttpKit.java

private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    final URL _url = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
    }//from   www  .j  ava  2s.co m

    conn.setRequestMethod(method);
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setConnectTimeout(19000);
    conn.setReadTimeout(19000);

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if (headers != null && !headers.isEmpty()) {
        for (final Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    return conn;
}

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  ww w .  j a  v a  2  s  .  c om

    //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.cloud.utils.UriUtils.java

public static Long getRemoteSize(String url) {
    Long remoteSize = (long) 0;
    HttpURLConnection httpConn = null;
    HttpsURLConnection httpsConn = null;
    try {/* ww  w. ja  v a  2 s .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: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/* ww  w  . ja  v  a2s .  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();
        }
    }
}