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:utils.httpUtil_inThread.java

/**
 * ?(?)/*from   ww w. ja va  2s  . com*/
 *
 * @return ?null?
 */
public byte[] HttpGetBitmap(String url, String cookie, int timeout_connection, int timeout_read) {
    byte[] bytes = null;
    InputStream is = null;
    try {
        //??
        if (timeout_connection <= 1000)
            timeout_connection = timeout_pic_connection;
        if (timeout_read < 1000)
            timeout_read = timeout_pic_read;

        URL bitmapURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) bitmapURL.openConnection();
        if (cookie != null && !cookie.equals(""))
            conn.setRequestProperty("Cookie", cookie); //cookie
        conn.setConnectTimeout(timeout_connection);
        conn.setReadTimeout(timeout_read);
        conn.setDoInput(true);
        conn.connect();

        //?
        is = conn.getInputStream();
        bytes = InputStreamUtils.InputStreamTOByte(is);
    } catch (Exception e) {
        abstract_LogUtil.e(this, "[]" + e.toString());
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (Exception e) {
            abstract_LogUtil.e(this, "[InputStream]");
        }
    }
    return bytes;
}

From source file:com.mtt.myapp.home.service.HomeService.java

/**
 * Get panel entries containing the entries from the given RSS
 * url.//from   w  w  w .  jav  a2 s. co m
 *
 * @param feedURL      rss url message
 * @param maxSize      max size
 * @param includeReply if including reply
 * @return {@link PanelEntry} list
 */
public List<PanelEntry> getPanelEntries(String feedURL, int maxSize, boolean includeReply) {
    SyndFeedInput input = new SyndFeedInput();
    XmlReader reader = null;
    HttpURLConnection feedConnection = null;
    try {
        List<PanelEntry> panelEntries = new ArrayList<PanelEntry>();
        URL url = new URL(feedURL);
        feedConnection = (HttpURLConnection) url.openConnection();
        feedConnection.setConnectTimeout(4000);
        feedConnection.setReadTimeout(4000);
        reader = new XmlReader(feedConnection);
        SyndFeed feed = input.build(reader);
        int count = 0;
        for (Object eachObj : feed.getEntries()) {
            SyndEntryImpl each = cast(eachObj);
            if (!includeReply && StringUtils.startsWithIgnoreCase(each.getTitle(), "Re: ")) {
                continue;
            }
            if (count++ > maxSize) {
                break;
            }
            PanelEntry entry = new PanelEntry();
            entry.setAuthor(each.getAuthor());
            entry.setLastUpdatedDate(
                    each.getUpdatedDate() == null ? each.getPublishedDate() : each.getUpdatedDate());
            entry.setTitle(each.getTitle());
            entry.setLink(each.getLink());
            panelEntries.add(entry);
        }
        Collections.sort(panelEntries);
        return panelEntries;
    } catch (Exception e) {
        LOG.error("Error while patching the feed entries for {} : {}", feedURL, e.getMessage());
    } finally {
        if (feedConnection != null) {
            feedConnection.disconnect();
        }
        IOUtils.closeQuietly(reader);
    }
    return Collections.emptyList();
}

From source file:com.baseproject.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * //from   w ww.jav a 2s  . c  o  m
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    // int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(request.getConnTimeoutMs());
    connection.setReadTimeout(request.getReadTimeoutMs());
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:com.urhola.vehicletracker.connection.mattersoft.MatterSoftLiveHelsinki.java

private HttpURLConnection getOpenedConnection(List<NameValuePair> params, String responseMethod)
        throws ConnectionException {
    HttpURLConnection urlConnection;
    try {/*from   w  ww.  ja  va  2s. co m*/
        URIBuilder b = new URIBuilder(BASE_URL);
        b.addParameters(params);
        URL url = b.build().toURL();
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod(responseMethod);
        urlConnection.setReadTimeout(TIME_OUT_LENGTH);
        urlConnection.setConnectTimeout(TIME_OUT_LENGTH);
        urlConnection.connect();
        int responseCode = urlConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(urlConnection.getResponseMessage());
        return urlConnection;
    } catch (URISyntaxException | IOException ex) {
        throw new ConnectionException(ex);
    }
}

From source file:msearch.filmlisten.MSFilmlisteLesen.java

private InputStream getInputStreamForLocation(String source) throws Exception {
    InputStream in;/* w ww. j a  v a  2  s .c  o  m*/
    long size = 0;
    final URI uri;
    if (source.startsWith("http")) {
        uri = new URI(source);
        //remote address for internet download
        HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestProperty("User-Agent", MSConfig.getUserAgent());
        if (conn.getResponseCode() < 400) {
            size = conn.getContentLengthLong();
        }
        in = new SizeInputStream(conn.getInputStream(), size, uri.toASCIIString());
    } else {
        //local file
        notifyProgress(source, "Download", PROGRESS_MAX);
        in = new FileInputStream(source);
    }

    return in;
}

From source file:com.eucalyptus.tokens.oidc.OidcDiscoveryCache.java

private OidcDiscoveryCachedResource fetchResource(final String url, final long timeNow,
        final OidcDiscoveryCachedResource cached) throws IOException {
    final URL location = new URL(url);
    final OidcResource oidcResource;
    { // setup url connection and resolve
        final HttpURLConnection conn = (HttpURLConnection) location.openConnection();
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setUseCaches(false);/*w  w  w  .  j av a 2s  . c  o  m*/
        if (cached != null) {
            if (cached.lastModified.isDefined()) {
                conn.setRequestProperty(HttpHeaders.IF_MODIFIED_SINCE, cached.lastModified.get());
            }
            if (cached.etag.isDefined()) {
                conn.setRequestProperty(HttpHeaders.IF_NONE_MATCH, cached.etag.get());
            }
        }
        oidcResource = resolve(conn);
    }

    // build cache entry from resource
    if (oidcResource.statusCode == 304) {
        return new OidcDiscoveryCachedResource(timeNow, cached);
    } else {
        return new OidcDiscoveryCachedResource(timeNow, Option.of(oidcResource.lastModifiedHeader),
                Option.of(oidcResource.etagHeader), ImmutableList.copyOf(oidcResource.certs), url,
                new String(oidcResource.content, StandardCharsets.UTF_8));
    }
}

From source file:com.jaredrummler.android.device.DeviceName.java

/** Download URL to String */
private static String downloadJson(String myurl) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;
    try {//from  w ww  . ja v a2s  .  c o  m
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        }
        return sb.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:ir.rasen.charsoo.controller.image_loader.core.download.BaseImageDownloader.java

/**
 * Create {@linkplain HttpURLConnection HTTP connection} for incoming URL
 *
 * @param url   URL to connect to/*from   w  ww .j ava 2  s .c  om*/
 * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *              DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@linkplain HttpURLConnection Connection} for incoming URL. Connection isn't established so it still configurable.
 * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected HttpURLConnection createConnection(String url, Object extra) throws IOException {
    String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);
    HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection();
    conn.setConnectTimeout(connectTimeout);
    conn.setReadTimeout(readTimeout);
    return conn;
}

From source file:com.exzogeni.dk.http.HttpTask.java

private void onPrepareConnectionInternal(HttpURLConnection cn) throws Exception {
    final URI uri = cn.getURL().toURI();
    cn.setRequestMethod(getMethodName());
    cn.setConnectTimeout(mTimeoutMs);//  w ww .ja v  a 2  s  . co  m
    cn.setReadTimeout(mTimeoutMs);
    final CookieManager cm = mHttpManager.getCookieManager();
    final Map<String, List<String>> cookies = cm.get(uri, new HashMap<String, List<String>>());
    for (final Map.Entry<String, List<String>> cookie : cookies.entrySet()) {
        for (final String value : cookie.getValue()) {
            cn.addRequestProperty(cookie.getKey(), value);
        }
    }
    for (final Map.Entry<String, List<String>> header : mHeaders.entrySet()) {
        for (final String value : header.getValue()) {
            cn.addRequestProperty(header.getKey(), value);
        }
    }
    onPrepareConnection(cn);
}

From source file:com.hly.component.download.DownloadTransaction.java

public HttpURLConnection getHttpConnetion(String url) throws IOException {
    URL urlObj = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setReadTimeout(READ_TIMEOUT);
    connection.setRequestMethod("GET");
    return connection;
}