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:org.mf.api.net.stack.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @return an open connection/*w ww  . j ava 2s . c o  m*/
 */
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);
    connection.setChunkedStreamingMode(0);

    // 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.ardnezar.lookapp.RoomParametersFetcher.java

private LinkedList<PeerConnection.IceServer> requestTurnServers(String url) throws IOException, JSONException {
    LinkedList<PeerConnection.IceServer> turnServers = new LinkedList<PeerConnection.IceServer>();
    Log.d(TAG, "Request TURN from: " + url);
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS);
    connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS);
    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new IOException("Non-200 response when requesting TURN server from " + url + " : "
                + connection.getHeaderField(null));
    }/*from  w  w  w.j  a v a2s. co m*/
    InputStream responseStream = connection.getInputStream();
    String response = drainStream(responseStream);
    connection.disconnect();
    Log.d(TAG, "TURN response: " + response);
    JSONObject responseJSON = new JSONObject(response);
    String username = responseJSON.getString("username");
    String password = responseJSON.getString("password");
    JSONArray turnUris = responseJSON.getJSONArray("uris");
    for (int i = 0; i < turnUris.length(); i++) {
        String uri = turnUris.getString(i);
        turnServers.add(new PeerConnection.IceServer(uri, username, password));
    }
    return turnServers;
}

From source file:com.graphhopper.http.NominatimGeocoder.java

HttpURLConnection openConnection(String url) throws IOException {
    HttpURLConnection hConn = (HttpURLConnection) new URL(url).openConnection();
    ;//from  w  ww. j a  va2 s .  c  o  m
    hConn.setRequestProperty("User-Agent", userAgent);
    hConn.setRequestProperty("content-charset", "UTF-8");
    hConn.setConnectTimeout(timeoutInMillis);
    hConn.setReadTimeout(timeoutInMillis);
    hConn.connect();
    return hConn;
}

From source file:com.risevision.ui.server.utils.MakeRequestServlet.java

public RequestResponse makeRequest(HttpServletRequest request) throws Exception {
    RequestResponse response = new RequestResponse();

    String requestUrl = request.getParameter("url");
    if ((requestUrl != null) && (!requestUrl.isEmpty())) {
        try {//from   ww w . j  a v a 2s . com
            URL payload_url = new URL(requestUrl.replace(" ", "+"));

            HttpURLConnection urlConnection = (HttpURLConnection) payload_url.openConnection();

            urlConnection.setReadTimeout(20000);
            urlConnection.setRequestMethod("GET");

            //            if ("oauth".equals(request.getParameter("authz")) && requestUrl.contains("api.twitter.com/1.1")) {
            //               signTwitterRequest(request, urlConnection);
            //            }

            response.responseBody = getResponseAsJson(urlConnection);
            response.responseCode = urlConnection.getResponseCode();

        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new Exception("Malformed URL, " + e.getMessage());
        } catch (Exception e) {
            //            e.printStackTrace();
            log.log(Level.SEVERE, e.getMessage(), e);
            //              log.severe("Exception - " + e.getMessage(), e);
        }
    }
    return response;
}

From source file:corner.payment.services.impl.processor.AlipayProcessor.java

@Override
public boolean verifyNotify(String notifyId) {
    if (notifyId == null) {
        throw new IllegalArgumentException("The notifyId is null");
    }/*w  w w  .j  av a  2  s .co m*/
    String alipayNotifyURL = String.format("%s?partner=%s&notify_id=%s", QUERY_URL, partner, notifyId);
    java.io.Closeable input = null;
    try {
        URL url = new URL(alipayNotifyURL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(false);
        urlConnection.setConnectTimeout(30 * 1000);
        urlConnection.setReadTimeout(30 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        input = in;
        String inputLine = in.readLine().toString();
        urlConnection.disconnect();
        if ("true".equalsIgnoreCase(inputLine)) {
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
    return false;
}

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

@Test
public final void testCanCreateSignedHEADUriFromPath() throws IOException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*from   w  ww  .j a va2 s.c  o  m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "HEAD", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("HEAD");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()));
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(TEST_DATA.length(), connection.getContentLength());
    } finally {
        connection.disconnect();
    }
}

From source file:org.devnexus.aerogear.HttpRestProvider.java

private HttpURLConnection prepareConnection(String id) {
    HttpURLConnection connection = connectionPreparer.get(id);
    connection.setReadTimeout(timeout);
    connection.setConnectTimeout(timeout);
    return connection;
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Downloads content from the specified url using specified proxy (or do not using it) and timeouts.
 * Returns null if there's an error./*  ww w .j  ava2 s.c o m*/
 *
 * @param url           url
 * @param proxy         proxy to use
 * @param readTimeout   read timeout
 * @param socketTimeout connection timeout
 * @return Downloaded string
 */
public static String downloadString(URL url, Proxy proxy, int readTimeout, int socketTimeout, String encoding) {
    HttpURLConnection connection = null;
    InputStream inputStream = null;

    try {
        connection = (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy));
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36");
        connection.setReadTimeout(readTimeout);
        connection.setConnectTimeout(socketTimeout);
        connection.connect();
        if (connection.getResponseCode() >= 400) {
            throw new IOException("Response status is " + connection.getResponseCode());
        }

        if (connection.getResponseCode() >= 301) {
            String location = connection.getHeaderField("Location");
            // HttpURLConnection does not follow redirects from HTTP to HTTPS
            // So we handle it manually
            return downloadString(new URL(location), proxy, readTimeout, socketTimeout, encoding);
        }

        if (connection.getResponseCode() == 204) {
            return StringUtils.EMPTY;
        }

        inputStream = connection.getInputStream();
        return IOUtils.toString(inputStream, encoding);
    } catch (IOException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Error downloading string from {}:\r\n", url, ex);
        } else {
            LOG.warn("Cannot download string from {}: {}", url, ex.getMessage());
        }
        // Ignoring exception
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

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

@Test
public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*  ww  w  . j  a va 2s.c o  m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

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

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("OPTIONS");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset());

            if (config.getMantaUser().contains("/")) {
                String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText);
                throw new SkipException(msg);
            }

            Assert.fail(errorText);
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(headers.get("Server").get(0), "Manta");
    } finally {
        connection.disconnect();
    }
}

From source file:com.epic.framework.implementation.tapjoy.TapjoyURLConnection.java

/**
 * Gets the file size of the specified resource from the HTTP header field "content-length"
 * @param url                     URL of the specified resource.
 * @return                        content-length, null otherwise.
 *///from w  w  w. j  av a2s  .  co m
public String getContentLength(String url) {
    String contentLength = null;
    try {
        String requestURL = url;

        // Replaces all spaces.
        requestURL = requestURL.replaceAll(" ", "%20");

        TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL);

        URL httpURL = new URL(requestURL);
        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        contentLength = connection.getHeaderField("content-length");
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString());
    }

    TapjoyLog.i(TAPJOY_URL_CONNECTION, "content-length: " + contentLength);

    return contentLength;
}