Java Code Examples for java.net.URLConnection#setReadTimeout()

The following examples show how to use java.net.URLConnection#setReadTimeout() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   File: RequireJsDataProvider.java    License: Apache License 2.0 6 votes vote down vote up
private void loadURL(URL url, Writer writer, Charset charset) throws IOException {
    if (charset == null) {
        charset = Charset.defaultCharset();
    }
    URLConnection con = url.openConnection();
    con.setConnectTimeout(URL_CONNECTION_TIMEOUT);
    con.setReadTimeout(URL_READ_TIMEOUT);
    con.connect();
    Reader r = new InputStreamReader(new BufferedInputStream(con.getInputStream()), charset);
    char[] buf = new char[2048];
    int read;
    while ((read = r.read(buf)) != -1) {
        writer.write(buf, 0, read);
    }
    r.close();
}
 
Example 2
Source Project: j2objc   File: URLConnectionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testMissingChunkBody() throws IOException {
    server.enqueue(new MockResponse()
            .setBody("5")
            .clearHeaders()
            .addHeader("Transfer-encoding: chunked")
            .setSocketPolicy(DISCONNECT_AT_END));
    server.play();

    URLConnection connection = server.getUrl("/").openConnection();

    // j2objc: See testNonHexChunkSize() above for why the timeout is needed.
    connection.setReadTimeout(1000);

    try {
        readAscii(connection.getInputStream(), Integer.MAX_VALUE);
        fail();
    } catch (IOException e) {
    }
}
 
Example 3
Source Project: netbeans   File: NodeJsDataProvider.java    License: Apache License 2.0 6 votes vote down vote up
private void loadURL(URL url, Writer writer, Charset charset) throws IOException {
    if (charset == null) {
        charset = Charset.defaultCharset();
    }
    URLConnection con = url.openConnection();
    con.setConnectTimeout(URL_CONNECTION_TIMEOUT);
    con.setReadTimeout(URL_READ_TIMEOUT);
    con.connect();
    try (Reader r = new InputStreamReader(new BufferedInputStream(con.getInputStream()), charset)) {
        char[] buf = new char[2048];
        int read;
        while ((read = r.read(buf)) != -1) {
            writer.write(buf, 0, read);
        }
    }
}
 
Example 4
public URLConnection openConnection(String url, Map<String, String> headers, int connectTimeout, int readTimeout) throws IOException {
    if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, String.format("%s opening connection: url [%s], headers [%s], connectTimeout [%s], readTimeout [%s]", getClass().getSimpleName(), url, headers, connectTimeout, readTimeout));
    }
    URLConnection connection = new URL(url).openConnection(Proxy.NO_PROXY);
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    if (connectTimeout < 0 || readTimeout < 0) {
        throw new IllegalArgumentException(
            String.format("Neither connectTimeout [%s] nor readTimeout [%s] can be less than 0 for URLConnection.", connectTimeout, readTimeout));
    }
    connection.setConnectTimeout(connectTimeout);
    connection.setReadTimeout(readTimeout);
    return connection;
}
 
Example 5
public boolean check(URL url) {
   if (url == null) {
      return false;
   }

   try {
      URLConnection connection = url.openConnection();
      connection.setReadTimeout(networkTimeout);
      InputStream is = connection.getInputStream();
      is.close();
      return true;
   } catch (Exception e) {
      ActiveMQUtilLogger.LOGGER.failedToCheckURL(e, url.toString());
      return false;
   }
}
 
Example 6
Source Project: Exoplayer_VLC   File: ManifestFetcher.java    License: Apache License 2.0 5 votes vote down vote up
private URLConnection configureConnection(URL url) throws IOException {
  URLConnection connection = url.openConnection();
  connection.setConnectTimeout(TIMEOUT_MILLIS);
  connection.setReadTimeout(TIMEOUT_MILLIS);
  connection.setDoOutput(false);
  connection.setRequestProperty("User-Agent", userAgent);
  connection.connect();
  return connection;
}
 
Example 7
Source Project: Android-Basics-Codes   File: WebImage.java    License: Artistic License 2.0 5 votes vote down vote up
private Bitmap getBitmapFromUrl(String url) {
    Bitmap bitmap = null;

    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        bitmap = BitmapFactory.decodeStream((InputStream) conn.getContent());
    } catch(Exception e) {
        e.printStackTrace();
    }

    return bitmap;
}
 
Example 8
private String get(String url) throws IOException {
    URLConnection connection = new URL(url).openConnection();
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setReadTimeout(READ_TIMEOUT);
    try (InputStream is = connection.getInputStream()) {
        return new String(is.readAllBytes());
    }
}
 
Example 9
Source Project: nyzoVerifier   File: RelayEndpoint.java    License: The Unlicense 5 votes vote down vote up
public void refresh() {
    // Only refresh web endpoints that are out of date.
    if (!isFileEndpoint && lastRefreshTimestamp < System.currentTimeMillis() - interval) {
        LogUtil.println("refreshing endpoint: " + sourceEndpoint);
        try {
            URLConnection connection = new URL(sourceEndpoint).openConnection();
            connection.setConnectTimeout(2000);  // 2 seconds
            connection.setReadTimeout(10000);    // 10 seconds
            if (connection.getContentLength() <= maximumSize) {
                byte[] result = new byte[connection.getContentLength()];
                ByteBuffer buffer = ByteBuffer.wrap(result);
                ReadableByteChannel channel = Channels.newChannel(connection.getInputStream());
                int bytesRead;
                int totalBytesRead = 0;
                while ((bytesRead = channel.read(buffer)) > 0) {
                    totalBytesRead += bytesRead;
                }
                channel.close();

                // Build the response and set the last-modified header.
                long refreshTimestamp = System.currentTimeMillis();
                cachedWebResponse = new EndpointResponse(result, connection.getContentType());
                cachedWebResponse.setHeader("Last-Modified", WebUtil.imfFixdateString(refreshTimestamp));
                cachedWebResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Set the refresh timestamp.
                lastRefreshTimestamp = refreshTimestamp;
            }
        } catch (Exception ignored) { }
    }
}
 
Example 10
Source Project: Eagle   File: InputStreamUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static InputStream openGZIPInputStream(URL url, int timeout) throws IOException {
	final URLConnection connection = url.openConnection();
	connection.setConnectTimeout(CONNECTION_TIMEOUT);
	connection.setReadTimeout(timeout);
	connection.addRequestProperty(GZIP_HTTP_HEADER, GZIP_COMPRESSION);
	return new GZIPInputStream(connection.getInputStream());
}
 
Example 11
Source Project: prayer-times-android   File: NVCTimes.java    License: Apache License 2.0 5 votes vote down vote up
public static String getName(String id) {
    try {
        URL url = new URL("http://namazvakti.com/XML.php?cityID=" + id);
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(3000);
        ucon.setReadTimeout(3000);

        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);


        BufferedReader reader = new BufferedReader(new InputStreamReader(bis, StandardCharsets.UTF_8));

        String line;


        while ((line = reader.readLine()) != null) {
            if (line.contains("cityNameTR")) {
                line = line.substring(line.indexOf("cityNameTR"));
                line = line.substring(line.indexOf("\"") + 1);
                line = line.substring(0, line.indexOf("\""));
                return line;

            }
        }
        reader.close();
    } catch (Exception ignore) {
    }
    return null;
}
 
Example 12
Source Project: XRTB   File: HttpPostGet.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Send an HTTP Post
 * @param targetURL
 *    String. The URL to transmit to.
 * @param data
 *            byte[]. The payload bytes.
 * @param connTimeout
 * 			  int. The connection timeout in ms
 * @param readTimeout
 * 			  int. The read timeout in ms.
 * @return byte[]. The contents of the POST return.
 * @throws Exception
 *             on network errors.
 */
public byte [] sendPost(String targetURL,  byte [] data, int connTimeout, int readTimeout) throws Exception {
	URLConnection connection = new URL(targetURL).openConnection();
	connection.setRequestProperty("Content-Type", "application/json");
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setConnectTimeout(connTimeout);
	connection.setReadTimeout(readTimeout);
	OutputStream output = connection.getOutputStream();
	
	try {
		output.write(data);
	} finally {
		try {
			output.close();
		} catch (IOException logOrIgnore) {
			logOrIgnore.printStackTrace();
		}
	}
	InputStream response = connection.getInputStream();
	
	http = (HttpURLConnection) connection;
	code = http.getResponseCode();
	
	String value = http.getHeaderField("Content-Encoding");
	
	if (value != null && value.equals("gzip")) {
		byte bytes [] = new byte[4096];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		GZIPInputStream gis = new GZIPInputStream(http.getInputStream());
		while(true) {
			int n = gis.read(bytes);
			if (n < 0) break;
			baos.write(bytes,0,n);
		}
		return baos.toByteArray();
	}
	
		

	byte [] b = getContents(response);
	if (b.length == 0)
		return null;
	return b;
}
 
Example 13
private static void setTimeouts(URLConnection connection, int socketTimeout) {
    connection.setConnectTimeout(socketTimeout);
    connection.setReadTimeout(socketTimeout);
}
 
Example 14
Source Project: netbeans   File: URLResourceRetriever.java    License: Apache License 2.0 4 votes vote down vote up
public InputStream getInputStreamOfURL(URL downloadURL, Proxy proxy) throws IOException{
    
    URLConnection ucn = null;
    
    // loop until no more redirections are 
    for (;;) {
        if (Thread.currentThread().isInterrupted()) {
            return null;
        }
        if(proxy != null) {
            ucn = downloadURL.openConnection(proxy);
        } else {
            ucn = downloadURL.openConnection();
        }
        HttpURLConnection hucn = doConfigureURLConnection(ucn);

        if(Thread.currentThread().isInterrupted())
            return null;
    
        ucn.connect();

        int rc = hucn.getResponseCode();
        boolean isRedirect = 
                rc == HttpURLConnection.HTTP_MOVED_TEMP ||
                rc == HttpURLConnection.HTTP_MOVED_PERM;
        if (!isRedirect) {
            break;
        }

        String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
        URL newURL = new URL(addr);
        if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
            throw new ResourceRedirectException(newURL);
        }
        downloadURL = newURL;
    }

    ucn.setReadTimeout(10000);
    InputStream is = ucn.getInputStream();
    streamLength = ucn.getContentLength();
    effectiveURL = ucn.getURL();
    return is;
    
}
 
Example 15
Source Project: j2objc   File: URLConnectionTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
     * We've had a bug where we forget the HTTP response when we see response
     * code 401. This causes a new HTTP request to be issued for every call into
     * the URLConnection.
     */
// TODO(tball): b/28067294
//    public void testUnauthorizedResponseHandling() throws IOException {
//        MockResponse response = new MockResponse()
//                .addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
//                .setResponseCode(401) // UNAUTHORIZED
//                .setBody("Unauthorized");
//        server.enqueue(response);
//        server.enqueue(response);
//        server.enqueue(response);
//        server.play();
//
//        URL url = server.getUrl("/");
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//
//        assertEquals(401, conn.getResponseCode());
//        assertEquals(401, conn.getResponseCode());
//        assertEquals(401, conn.getResponseCode());
//        assertEquals(1, server.getRequestCount());
//    }

    public void testNonHexChunkSize() throws IOException {
        server.enqueue(new MockResponse()
                .setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n")
                .clearHeaders()
                .addHeader("Transfer-encoding: chunked"));
        server.play();

        URLConnection connection = server.getUrl("/").openConnection();

        // j2objc: URLConnection does not time out by default (i.e. getReadTimeout() returns 0).
        // When we create the native NSMutableURLRequest, we set its timeoutInterval to
        // JavaLangDouble_MAX_VALUE to make it never time out. This is problematic if the response
        // uses chunked transfer encoding, as the NSURLSessionDataTask is unable to make progress
        // and the read will never finish. A definite timeout is therefore needed here.
        connection.setReadTimeout(1000);

        try {
            readAscii(connection.getInputStream(), Integer.MAX_VALUE);
            fail();
        } catch (IOException e) {
        }
    }
 
Example 16
Source Project: iaf   File: ClassUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static InputStream urlToStream(URL url, int timeoutMs) throws IOException {
	URLConnection conn = url.openConnection();
	conn.setConnectTimeout(timeoutMs);
	conn.setReadTimeout(timeoutMs);
	return conn.getInputStream(); //SCRV_269S#072 //SCRV_286S#077
}
 
Example 17
Source Project: wandora   File: Qaop.java    License: GNU General Public License v3.0 4 votes vote down vote up
private InputStream start_download(String f) throws IOException {
    Qaop a = qaop;
    a.dl_length = a.dl_loaded = 0;
    a.dl_text = f;

    URL u = new URL(f);

    f = u.getFile();
    int i = f.lastIndexOf('/');
    if (i >= 0) {
        f = f.substring(i + 1);
    }

    a.dl_text = f;
    a.repaint(200);

    URLConnection c = u.openConnection();
    try {
        c.setConnectTimeout(15000);
        c.setReadTimeout(10000);
    } catch (Error e) {
    }

    if (c instanceof java.net.HttpURLConnection) {
        int x = ((java.net.HttpURLConnection) c).getResponseCode();
        if (x < 200 || x > 299) {
            throw new FileNotFoundException();
        }
    }

    check_type(c.getContentType(), f);

    String s = c.getContentEncoding();
    if (s != null && s.contains("gzip")) {
        gz = true;
    }

    int l = c.getContentLength();
    qaop.dl_length = l > 0 ? l : 1 << 16;

    file = u.getRef();
    return c.getInputStream();
}
 
Example 18
/**
 * Opens a new or recycled connection to the HTTP server.
 */
public HessianConnection open(URL url)
    throws IOException
{
    if (log.isLoggable(Level.FINER))
        log.finer(this + " open(" + url + ")");

    URLConnection conn = url.openConnection();

    // HttpURLConnection httpConn = (HttpURLConnection) conn;
    // httpConn.setRequestMethod("POST");
    // conn.setDoInput(true);

    long connectTimeout = _proxyFactory.getConnectTimeout();

    if (connectTimeout >= 0)
        conn.setConnectTimeout((int) connectTimeout);

    conn.setDoOutput(true);

    long readTimeout = _proxyFactory.getReadTimeout();

    if (readTimeout > 0) {
        try {
            conn.setReadTimeout((int) readTimeout);
        } catch (Throwable e) {
        }
    }

    /*
    // Used chunked mode when available, i.e. JDK 1.5.
    if (_proxyFactory.isChunkedPost() && conn instanceof HttpURLConnection) {
      try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;

        httpConn.setChunkedStreamingMode(8 * 1024);
      } catch (Throwable e) {
      }
    }
    */

    return new HessianURLConnection(url, conn);
}
 
Example 19
Source Project: bidder   File: HttpPostGet.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Send an HTTP Post
 * @param targetURL
 *    String. The URL to transmit to.
 * @param data
 *            byte[]. The payload bytes.
 * @param connTimeout
 * 			  int. The connection timeout in ms
 * @param readTimeout
 * 			  int. The read timeout in ms.
 * @return byte[]. The contents of the POST return.
 * @throws Exception
 *             on network errors.
 */
public byte [] sendPost(String targetURL,  byte [] data, int connTimeout, int readTimeout) throws Exception {
	URLConnection connection = new URL(targetURL).openConnection();
	connection.setRequestProperty("Content-Type", "application/json");
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setConnectTimeout(connTimeout);
	connection.setReadTimeout(readTimeout);
	OutputStream output = connection.getOutputStream();
	
	try {
		output.write(data);
	} finally {
		try {
			output.close();
		} catch (IOException logOrIgnore) {
			logOrIgnore.printStackTrace();
		}
	}
	InputStream response = connection.getInputStream();
	
	http = (HttpURLConnection) connection;
	code = http.getResponseCode();
	
	String value = http.getHeaderField("Content-Encoding");
	
	if (value != null && value.equals("gzip")) {
		byte bytes [] = new byte[4096];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		GZIPInputStream gis = new GZIPInputStream(http.getInputStream());
		while(true) {
			int n = gis.read(bytes);
			if (n < 0) break;
			baos.write(bytes,0,n);
		}
		return baos.toByteArray();
	}
	
		

	byte [] b = getContents(response);
	if (b.length == 0)
		return null;
	return b;
}
 
Example 20
Source Project: hadoop   File: URLConnectionFactory.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Sets timeout parameters on the given URLConnection.
 * 
 * @param connection
 *          URLConnection to set
 * @param socketTimeout
 *          the connection and read timeout of the connection.
 */
private static void setTimeouts(URLConnection connection, int socketTimeout) {
  connection.setConnectTimeout(socketTimeout);
  connection.setReadTimeout(socketTimeout);
}