Java Code Examples for java.net.URLConnection#setReadTimeout()
The following examples show how to use
java.net.URLConnection#setReadTimeout() .
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 check out the related API usage on the sidebar.
Example 1
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 6 votes |
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 2
Source File: RequireJsDataProvider.java From netbeans with Apache License 2.0 | 6 votes |
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 3
Source File: NodeJsDataProvider.java From netbeans with Apache License 2.0 | 6 votes |
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
Source File: NetworkHealthCheck.java From activemq-artemis with Apache License 2.0 | 6 votes |
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 5
Source File: BaseStreamProvider.java From openshift-ping with Apache License 2.0 | 6 votes |
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 6
Source File: NVCTimes.java From prayer-times-android with Apache License 2.0 | 5 votes |
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 7
Source File: InputStreamUtils.java From Eagle with Apache License 2.0 | 5 votes |
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 8
Source File: RelayEndpoint.java From nyzoVerifier with The Unlicense | 5 votes |
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 9
Source File: RestCustomerDao.java From Design-Patterns-and-SOLID-Principles-with-Java with MIT License | 5 votes |
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 10
Source File: WebImage.java From Android-Basics-Codes with Artistic License 2.0 | 5 votes |
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 11
Source File: ManifestFetcher.java From Exoplayer_VLC with Apache License 2.0 | 5 votes |
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 12
Source File: URLResourceRetriever.java From netbeans with Apache License 2.0 | 4 votes |
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 13
Source File: URLConnectionTest.java From j2objc with Apache License 2.0 | 4 votes |
/** * 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 14
Source File: ClassUtils.java From iaf with Apache License 2.0 | 4 votes |
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 15
Source File: SecureClientUtils.java From incubator-atlas with Apache License 2.0 | 4 votes |
private static void setTimeouts(URLConnection connection, int socketTimeout) { connection.setConnectTimeout(socketTimeout); connection.setReadTimeout(socketTimeout); }
Example 16
Source File: Qaop.java From wandora with GNU General Public License v3.0 | 4 votes |
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 17
Source File: HessianURLConnectionFactory.java From sofa-hessian with Apache License 2.0 | 4 votes |
/** * 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 18
Source File: HttpPostGet.java From XRTB with Apache License 2.0 | 4 votes |
/** * 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 19
Source File: HttpPostGet.java From bidder with Apache License 2.0 | 4 votes |
/** * 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 File: URLConnectionFactory.java From hadoop with Apache License 2.0 | 2 votes |
/** * 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); }