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.lovebridge.library.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 *
 * @param url//from   w ww.  ja va 2s  .  c  o m
 * @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(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    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:ly.count.android.api.ConnectionProcessor.java

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    final String urlStr = serverURL_ + "/i?" + eventData;
    final URL url = new URL(urlStr);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);/*from  w  w w .j ava 2s .  c o  m*/
    conn.setDoInput(true);
    String picturePath = UserData.getPicturePathFromQuery(url);
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.d(Countly.TAG, "Got picturePath: " + picturePath);
    }
    if (!picturePath.equals("")) {
        //Uploading files:
        //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests

        File binaryFile = new File(picturePath);
        conn.setDoOutput(true);
        // Just generate some unique random value.
        String boundary = Long.toHexString(System.currentTimeMillis());
        // Line separator required by multipart/form-data.
        String CRLF = "\r\n";
        String charset = "UTF-8";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName()
                + "\"").append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        FileInputStream fileInputStream = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        output.flush(); // Important before continuing with writer!
        writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        fileInputStream.close();

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
    } else {
        conn.setDoOutput(false);
    }
    return conn;
}

From source file:si.mazi.rescu.HttpTemplate.java

/**
 * @param urlString/*  w  w  w. j av  a2  s  . c o m*/
 * @return a HttpURLConnection instance
 * @throws IOException
 */
protected HttpURLConnection getHttpURLConnection(String urlString) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection(proxy);
    if (readTimeout > 0) {
        connection.setReadTimeout(readTimeout);
    }
    return connection;
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedURIWithEncodedCharacters() throws IOException {
    final String path = testPathPrefix + " quack ";

    mantaClient.put(path, TEST_DATA, UTF_8);
    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    final URI uri = mantaClient.getAsSignedURI(path, "GET", Instant.now().plus(Duration.ofHours(1)));
    final HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();

    try (final InputStream is = conn.getInputStream()) {
        conn.setReadTimeout(3000);
        conn.connect();//from   ww w. j  a  va2  s.c  o m

        Assert.assertEquals(conn.getResponseCode(), HttpStatus.SC_OK);
        Assert.assertEquals(IOUtils.toString(is, UTF_8), TEST_DATA);
    } finally {
        conn.disconnect();
    }
}

From source file:com.esminis.server.library.service.server.installpackage.InstallerPackage.java

private void download(Context context, com.esminis.server.library.model.InstallPackage model, File fileOutput)
        throws Throwable {
    sendBroadcast(context, STATE_DOWNLOAD, 0);
    final HttpURLConnection connection = (HttpURLConnection) new URL(model.uri).openConnection();
    connection.setConnectTimeout(20000);
    connection.setReadTimeout(10000);
    FileOutputStream output = null;
    try {/*from  ww w  . jav a  2s  .  c o m*/
        output = new FileOutputStream(fileOutput);
        InputStream inputStream = connection.getInputStream();
        final float fileSize = (float) connection.getContentLength();
        byte[] buffer = new byte[1024 * 128];
        long count = 0;
        int n;
        long time = System.currentTimeMillis();
        while (-1 != (n = inputStream.read(buffer))) {
            count += n;
            output.write(buffer, 0, n);
            if (System.currentTimeMillis() - time >= 1000) {
                sendBroadcast(context, STATE_DOWNLOAD, (((float) count) / fileSize) * 0.99f);
                time = System.currentTimeMillis();
            }
        }
        sendBroadcast(context, STATE_DOWNLOAD, 0.99f);
    } finally {
        connection.disconnect();
        if (output != null) {
            try {
                output.close();
            } catch (IOException ignored) {
            }
        }
    }
    if (model.hash != null && !model.hash.equals(Utils.hash(fileOutput))) {
        throw new Exception("Downloaded file was corrupted: " + model.uri);
    }
    sendBroadcast(context, STATE_DOWNLOAD, 1);
}

From source file:com.android.volley.util.HurlStack.java

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

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    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:id.nci.stm_9.HkpKeyServer.java

private String query(String request) throws QueryException, HttpError {
    InetAddress ips[];/*from  w ww. jav  a  2 s  .c o m*/
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryException("querying server(s) for '" + mHost + "' failed");
}

From source file:com.cloudbees.mtslaves.client.RemoteReference.java

protected HttpURLConnection open(String relUrl) throws IOException {
    URL u = getEntityUrl(relUrl);
    HttpURLConnection con = (HttpURLConnection) u.openConnection();
    con.addRequestProperty("Accept", "application/json");
    this.token.authorizeRequest(con);
    con.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
    con.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);

    return con;// w  ww  . j a va 2s.  c  o m
}

From source file:net.peterkuterna.appengine.apps.devoxxsched.util.Md5Calculator.java

private byte[] getResponse(final String requestUri) {
    try {//  w w w  . ja va  2  s  . c  om
        URL url = new URL(requestUri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-agent", "Devoxx Schedule AppEngine Backend");
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(120 * 1000);
        connection.setRequestProperty("Cache-Control", "no-cache,max-age=0");
        connection.setRequestProperty("Pragma", "no-cache");
        InputStream response = connection.getInputStream();
        log.info("response = " + connection.getResponseCode());
        if (connection.getResponseCode() == 200) {
            return IOUtils.toByteArray(response);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:io.pivotal.demo.smartgrid.frontend.timeseries.AggregateCounterTimeSeriesRepository.java

private void pingXdServer() {
    try {/*from ww  w.j av a2 s  .  c o m*/
        HttpURLConnection con = (HttpURLConnection) new URL(xdServerBaseUrl).openConnection();
        con.setRequestMethod("HEAD");

        int timeout = 2000;

        con.setReadTimeout(timeout);
        con.setConnectTimeout(timeout);

        int responseCode = con.getResponseCode();

        if (responseCode != HttpURLConnection.HTTP_OK) {
            LOG.error("Bad response from server: {} Response: {}", xdServerBaseUrl, responseCode);
        }
    } catch (Exception ex) {
        LOG.error("Could not connect to server: {} Error: {}: {}", xdServerBaseUrl,
                ex.getClass().getSimpleName(), ex.getMessage());
    }
}