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.gaze.webpaser.StackWidgetService.java

private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    // from SD cache
    // CHECK : if trying to decode file which not exist in cache return null
    Bitmap b = decodeFile(f);/*from  ww w  .j ava2  s .  c  o m*/
    if (b != null)
        return b;

    // Download image file from web
    try {

        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();

        // Constructs a new FileOutputStream that writes to file
        // if file not exist then it will create file
        OutputStream os = new FileOutputStream(f);

        // See Utils class CopyStream method
        // It will each pixel from input stream and
        // write pixels to output stream (file)
        Util.CopyStream(is, os);

        os.close();
        conn.disconnect();

        // Now file created and going to resize file with defined height
        // Decodes image and scales it to reduce memory consumption
        bitmap = decodeFile(f);

        return bitmap;

    } catch (Throwable ex) {
        ex.printStackTrace();
        if (ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

From source file:net.bither.bitherj.api.DownloadFile.java

private boolean downloadUrlToFile(String urlString, File file) throws IOException, HttpRequestException {
    //  disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    OutputStream outputStream = null;
    try {//from w w  w.j  a  v a2 s  . co m
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(HttpSetting.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(HttpSetting.HTTP_SO_TIMEOUT);
        String sCookies = getCookie();

        urlConnection.setRequestProperty("Cookie", sCookies);
        int httpCode = urlConnection.getResponseCode();
        if (httpCode != 200) {
            throw new HttpRequestException("http exception " + httpCode);
        }

        outputStream = new FaultHidingOutputStream(new FileOutputStream(file));
        in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (final IOException e) {
        throw e;
    } finally {

        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (hasErrors) {
                deleteIfExists(file);
            }

        } catch (final IOException e) {
            throw e;
        }
    }
}

From source file:com.paymaya.sdk.android.common.network.AndroidClient.java

private HttpURLConnection initializeConnection(Request request) {
    try {//from w ww .  j  a v  a  2s.  c o m
        HttpURLConnection conn = (HttpURLConnection) request.getUrl().openConnection();
        if (conn instanceof HttpsURLConnection) {
            try {
                SSLHelper.injectSSLSocketFactory((HttpsURLConnection) conn, SSLHelper.PROTOCOL_TLS_V_1_2);
            } catch (NoSuchAlgorithmException | KeyManagementException ignored) {
                Log.w(TAG, "TLS V1.2 is not supported.");
            }
        }
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setRequestProperty(CONTENT_TYPE, CONTENT_TYPE_JSON);
        if (request.getHeaders() != null) {
            for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        return conn;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        throw new RuntimeException("Invalid URL: " + request.getUrl());
    }
}

From source file:org.fabric3.admin.interpreter.communication.DomainConnectionImpl.java

private HttpURLConnection createAddressConnection(String address, String path, String verb)
        throws CommunicationException {

    try {/*from  www .  j  a v  a2s .c  o m*/
        URL url = createUrl(address + path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod(verb);
        connection.setRequestProperty("Content-type", "application/json");
        connection.setReadTimeout(TIMEOUT);

        setBasicAuth(connection);

        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            setSocketFactory(httpsConnection);
        }

        return connection;
    } catch (IOException e) {
        throw new CommunicationException(e);
    }
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

public Path download(ChromiumVersion version) {
    final Path destinationRoot = getChromiumPath(version);
    final Path executable = getExecutable(version);

    String url;/*from ww  w  . j  av  a2  s  .  com*/
    if (WINDOWS) {
        url = format("%s/Win_x64/%d/chrome-win.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (LINUX) {
        url = format("%s/Linux_x64/%d/chrome-linux.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (MAC) {
        url = format("%s/Mac/%d/chrome-mac.zip", DOWNLOAD_HOST, version.getRevision());
    } else {
        throw new CdpException("Unsupported OS found - " + OS);
    }

    try {
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("HEAD");
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        if (conn.getResponseCode() != 200) {
            throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
        }
        long contentLength = conn.getHeaderFieldLong("x-goog-stored-content-length", 0);
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")) + "-r"
                + version.getRevision() + ".zip";
        Path archive = get(getProperty("java.io.tmpdir")).resolve(fileName);
        if (exists(archive) && contentLength != size(archive)) {
            delete(archive);
        }
        if (!exists(archive)) {
            logger.info("Downloading Chromium [revision=" + version.getRevision() + "] 0%");
            u = new URL(url);
            if (conn.getResponseCode() != 200) {
                throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
            conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            Thread thread = null;
            AtomicBoolean halt = new AtomicBoolean(false);
            Runnable progress = () -> {
                try {
                    long fileSize = size(archive);
                    logger.info("Downloading Chromium [revision={}] {}%", version.getRevision(),
                            round((fileSize * 100L) / contentLength));
                } catch (IOException e) {
                    // ignore
                }
            };
            try (InputStream is = conn.getInputStream()) {
                logger.info("Download location: " + archive.toString());
                thread = new Thread(() -> {
                    while (true) {
                        try {
                            if (halt.get()) {
                                break;
                            }
                            progress.run();
                            sleep(1000);
                        } catch (Throwable e) {
                            // ignore
                        }
                    }
                });
                thread.setName("cdp4j");
                thread.setDaemon(true);
                thread.start();
                copy(conn.getInputStream(), archive);
            } finally {
                if (thread != null) {
                    progress.run();
                    halt.set(true);
                }
            }
        }
        logger.info("Extracting to: " + destinationRoot.toString());
        if (exists(archive)) {
            createDirectories(destinationRoot);
            unpack(archive.toFile(), destinationRoot.toFile());
        }

        if (!exists(executable) || !isExecutable(executable)) {
            throw new CdpException("Chromium executable not found: " + executable.toString());
        }

        if (!WINDOWS) {
            Set<PosixFilePermission> permissions = getPosixFilePermissions(executable);
            if (!permissions.contains(OWNER_EXECUTE)) {
                permissions.add(OWNER_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
            if (!permissions.contains(GROUP_EXECUTE)) {
                permissions.add(GROUP_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
        }
    } catch (IOException e) {
        throw new CdpException(e);
    }
    return executable;
}

From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java

/**
 * Initialises a HTTP POST connection/*from w  w  w. ja va2  s  . com*/
 * @param urlStr the url to connect to
 * @return an initialised POST connection
 * @throws IOException when there's some kind of communication problem
 */
protected HttpURLConnection initPostConnection(String urlStr) throws IOException {

    URL url = new URL(urlStr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    connection.setReadTimeout(READ_TIMEOUT);

    // required to ensure the connection is not reused. When not set, spurious
    // intermittent problems (double posts, missing posts) occur under heavy load.
    connection.setRequestProperty("Connection", "close");
    return connection;
}

From source file:net.bither.api.DownloadFile.java

private boolean downloadUrlToFile(String urlString, File file) throws IOException, HttpRequestException {
    disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    OutputStream outputStream = null;
    try {//  w  w  w  . j ava  2  s  .co  m
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(HttpSetting.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(HttpSetting.HTTP_SO_TIMEOUT);
        String sCookies = getCookie();
        LogUtil.d("cookie", sCookies);
        urlConnection.setRequestProperty("Cookie", sCookies);
        int httpCode = urlConnection.getResponseCode();
        if (httpCode != 200) {
            throw new HttpRequestException("http exception " + httpCode);
        }

        outputStream = new FaultHidingOutputStream(new FileOutputStream(file));
        in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (final IOException e) {
        throw e;
    } finally {

        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (hasErrors) {
                deleteIfExists(file);
            }

        } catch (final IOException e) {
            throw e;
        }
    }
}

From source file:com.cloudera.nav.sdk.examples.lineage3.LineageExport.java

private HttpURLConnection createHttpConnection(ClientConfig config, Set<String> entityIds) throws IOException {
    String navUrl = config.getNavigatorUrl();
    String serverUrl = navUrl + (navUrl.endsWith("/") ? LINEAGE_EXPORT_API : "/" + LINEAGE_EXPORT_API);
    String queryParamString = String.format(LINEAGE_EXPORT_API_QUERY_PARAMS,
            URLEncoder.encode(direction, charset), // direction of lineage
            URLEncoder.encode(length, charset), // length of lineage
            URLEncoder.encode(lineageOptions, charset)); // Apply all filters

    URL url = new URL(serverUrl + queryParamString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    String userpass = config.getUsername() + ":" + config.getPassword();
    String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    conn.addRequestProperty("Authorization", basicAuth);
    conn.addRequestProperty("Content-Type", "application/json");
    conn.addRequestProperty("Accept", "application/json");
    conn.setReadTimeout(0);
    conn.setRequestMethod("POST");

    // entityIds to pass in the request body
    String postData = constructEntityIdsAsCSV(entityIds);
    postData = "[" + postData + "]";
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");
    conn.addRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
    conn.setDoOutput(true);/*from ww  w .ja  v  a2  s. com*/
    conn.getOutputStream().write(postDataBytes);

    return conn;
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

private HttpURLConnection buildConnection(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);//from   ww  w .j  a v a2  s .  co m
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);
    connection.setUseCaches(false);

    // Set the authorization header if one has been specified
    if (authorization != null) {
        connection.setRequestProperty("Authorization", authorization);
    }

    return connection;
}