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:com.gmobi.poponews.util.HttpHelper.java

public static int download(String url, File file) {
    HttpURLConnection connection = null;
    int length = 0;
    try {//from  www . j  av a 2  s.  com
        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.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   w  w w  .  j  av  a2 s  .c  o  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

private static Response doRequest(String url, Object raw, int method) {
    disableSslCheck();//  w ww  .  ja  va 2 s . c  o 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:org.akita.io.HttpInvoker.java

/**
 * post with files using URLConnection Impl
 * @param actionUrl URL to post//from w  w  w  . ja  v a 2 s . c  o  m
 * @param params params to post
 * @param files files to post, support multi-files
 * @return response in String format
 * @throws IOException
 */
public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params,
        Map<String, File> files) throws AkInvokeException {
    try {
        Log.v(TAG, "post:" + actionUrl);
        if (params != null) {
            Log.v(TAG, "params:=====================");
            for (NameValuePair nvp : params) {
                Log.v(TAG, nvp.getName() + "=" + nvp.getValue());
            }
            Log.v(TAG, "params end:=====================");
        }

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setReadTimeout(60 * 1000);
        conn.setDoInput(true); // permit input
        conn.setDoOutput(true); // permit output
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post Method
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // firstly string params to add
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nameValuePair : params) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(nameValuePair.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // send files secondly
        if (files != null) {
            int num = 0;
            for (Map.Entry<String, File> file : files.entrySet()) {
                num++;
                if (file.getKey() == null || file.getValue() == null)
                    continue;
                else {
                    if (!file.getValue().exists()) {
                        throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND,
                                "The file to upload is not found.");
                    }
                }
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }
        }

        // request end flag
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // get response code
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line + "\n");
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();
        Log.v(TAG, "response:" + sb2.toString());
        return sb2.toString();
    } catch (IOException ioe) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe);
    }
}

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);
    }/*from w ww  .ja v a2 s  .c  om*/

    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.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

public static String downloadFileAsString(String url) {
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {/*from   www. ja  v a  2  s  .com*/
        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:Main.java

public static String getPosthtml(String posturl, String postData, String encode) {

    String html = "";
    URL url;/*w ww  .ja v  a 2  s .c  o m*/
    try {
        url = new URL(posturl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("User-Agent", userAgent);

        String postDataStr = postData;
        byte[] bytes = postDataStr.getBytes("utf-8");
        connection.setRequestProperty("Content-Length", "" + bytes.length);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setDoOutput(true);
        connection.setReadTimeout(timeout);
        connection.setFollowRedirects(true);
        connection.connect();
        OutputStream outStrm = connection.getOutputStream();
        outStrm.write(bytes);
        outStrm.flush();
        outStrm.close();
        InputStream inStrm = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, encode));

        String temp = "";
        while ((temp = br.readLine()) != null) {
            html += (temp + '\n');
        }
        br.close();
        connection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return html;

}

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  www  . j a  v a2 s  .com*/
    return getInputStream(httpUrlConnection);

}

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);
    }// ww  w . ja  v  a2 s. 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.sunchenbin.store.feilong.core.net.URLConnectionUtil.java

/**
 * Prepare connection./* ww w.ja  v  a 2s. 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());
        }
    }
}