java.net.URLConnection#setReadTimeout ( )源码实例Demo

下面列出了java.net.URLConnection#setReadTimeout ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netbeans   文件: RequireJsDataProvider.java
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();
}
 
源代码2 项目: j2objc   文件: URLConnectionTest.java
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) {
    }
}
 
源代码3 项目: netbeans   文件: NodeJsDataProvider.java
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);
        }
    }
}
 
源代码4 项目: openshift-ping   文件: BaseStreamProvider.java
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;
}
 
源代码5 项目: activemq-artemis   文件: NetworkHealthCheck.java
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;
   }
}
 
源代码6 项目: Exoplayer_VLC   文件: ManifestFetcher.java
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;
}
 
源代码7 项目: Android-Basics-Codes   文件: WebImage.java
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;
}
 
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());
    }
}
 
源代码9 项目: nyzoVerifier   文件: RelayEndpoint.java
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) { }
    }
}
 
源代码10 项目: Eagle   文件: InputStreamUtils.java
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());
}
 
源代码11 项目: prayer-times-android   文件: NVCTimes.java
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;
}
 
源代码12 项目: XRTB   文件: HttpPostGet.java
/**
 * 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;
}
 
源代码13 项目: incubator-atlas   文件: SecureClientUtils.java
private static void setTimeouts(URLConnection connection, int socketTimeout) {
    connection.setConnectTimeout(socketTimeout);
    connection.setReadTimeout(socketTimeout);
}
 
源代码14 项目: netbeans   文件: URLResourceRetriever.java
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;
    
}
 
源代码15 项目: j2objc   文件: URLConnectionTest.java
/**
     * 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) {
        }
    }
 
源代码16 项目: iaf   文件: ClassUtils.java
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
}
 
源代码17 项目: wandora   文件: Qaop.java
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();
}
 
源代码18 项目: sofa-hessian   文件: HessianURLConnectionFactory.java
/**
 * 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);
}
 
源代码19 项目: bidder   文件: HttpPostGet.java
/**
 * 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;
}
 
源代码20 项目: hadoop   文件: URLConnectionFactory.java
/**
 * 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);
}