java.net.URLConnection.setReadTimeout()方法的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(10.7k)|赞(0)|评价(0)|浏览(534)

本文整理了Java中java.net.URLConnection.setReadTimeout()方法的一些代码示例,展示了URLConnection.setReadTimeout()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。URLConnection.setReadTimeout()方法的具体详情如下:
包路径:java.net.URLConnection
类名称:URLConnection
方法名:setReadTimeout

URLConnection.setReadTimeout介绍

[英]Sets the maximum time to wait for an input stream read to complete before giving up. Reading will fail with a SocketTimeoutException if the timeout elapses before data becomes available. The default value of 0 disables read timeouts; read attempts will block indefinitely.
[中]设置放弃前等待输入流读取完成的最长时间。如果在数据可用之前超时,读取将失败,并出现SocketTimeoutException。默认值0将禁用读取超时;读取尝试将无限期阻止。

代码示例

代码示例来源:origin: stackoverflow.com

URL url = new URL(urlPath);
URLConnection con = url.openConnection();
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(readTimeout);
InputStream in = con.getInputStream();

代码示例来源:origin: lingochamp/FileDownloader

public FileDownloadUrlConnection(URL url, Configuration configuration) throws IOException {
  if (configuration != null && configuration.proxy != null) {
    mConnection = url.openConnection(configuration.proxy);
  } else {
    mConnection = url.openConnection();
  }
  if (configuration != null) {
    if (configuration.readTimeout != null) {
      mConnection.setReadTimeout(configuration.readTimeout);
    }
    if (configuration.connectTimeout != null) {
      mConnection.setConnectTimeout(configuration.connectTimeout);
    }
  }
}

代码示例来源:origin: wildfly/wildfly

public boolean check(URL url) {
 try {
   URLConnection connection = url.openConnection();
   connection.setReadTimeout(networkTimeout);
   InputStream is = connection.getInputStream();
   is.close();
   return true;
 } catch (Exception e) {
   ActiveMQUtilLogger.LOGGER.failedToCheckURL(e, url == null ? " " : url.toString());
   return false;
 }
}

代码示例来源:origin: stackoverflow.com

try
  final URL aUrl = new URL(url);
  final URLConnection conn = aUrl.openConnection();
  conn.setReadTimeout(15 * 1000);  // timeout for reading the google maps data: 15 secs
  conn.connect();

代码示例来源:origin: cSploit/android

protected void writeCall(String methodName, Object[] args) throws IOException {
 huc = u.openConnection();
 huc.setDoOutput(true);
 huc.setDoInput(true);
 huc.setUseCaches(false);
 huc.setRequestProperty("Content-Type", "binary/message-pack");
 huc.setReadTimeout(0);
 OutputStream os = huc.getOutputStream();
 Packer pk = msgpack.createPacker(os);
 pk.writeArrayBegin(args.length+1);
 pk.write(methodName);
 for (Object arg : args)
  pk.write(arg);
 pk.writeArrayEnd();
 pk.close();
 os.close();
}

代码示例来源:origin: osmandapp/Osmand

if (request.referer != null)
  connection.setRequestProperty("Referer", request.referer); //$NON-NLS-1$
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setReadTimeout(CONNECTION_TIMEOUT);
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8 * 1024);
request.saveTile(inputStream);
if (log.isDebugEnabled()) {

代码示例来源:origin: jenkinsci/jenkins

con.setReadTimeout(PLUGIN_DOWNLOAD_READ_TIMEOUT);
           sha256 != null ? new DigestOutputStream(
               sha512 != null ? new DigestOutputStream(_out, sha512) : _out, sha256) : _out, sha1) : _out;
   InputStream in = con.getInputStream();
   CountingInputStream cin = new CountingInputStream(in)) {
  while ((len = cin.read(buf)) >= 0) {

代码示例来源:origin: lingochamp/FileDownloader

@Test
public void construct_noConfiguration_noAssigned() throws IOException {
  FileDownloadUrlConnection.Creator creator = new FileDownloadUrlConnection.Creator();
  creator.create("http://blog.dreamtobe.cn");
  verify(mConnection, times(0)).setConnectTimeout(anyInt());
  verify(mConnection, times(0)).setReadTimeout(anyInt());
}

代码示例来源:origin: commons-io/commons-io

/**
 * Copies bytes from the URL <code>source</code> to a file
 * <code>destination</code>. The directories up to <code>destination</code>
 * will be created if they don't already exist. <code>destination</code>
 * will be overwritten if it already exists.
 *
 * @param source            the <code>URL</code> to copy bytes from, must not be {@code null}
 * @param destination       the non-directory <code>File</code> to write bytes to
 *                          (possibly overwriting), must not be {@code null}
 * @param connectionTimeout the number of milliseconds until this method
 *                          will timeout if no connection could be established to the <code>source</code>
 * @param readTimeout       the number of milliseconds until this method will
 *                          timeout if no data could be read from the <code>source</code>
 * @throws IOException if <code>source</code> URL cannot be opened
 * @throws IOException if <code>destination</code> is a directory
 * @throws IOException if <code>destination</code> cannot be written
 * @throws IOException if <code>destination</code> needs creating but can't be
 * @throws IOException if an IO error occurs during copying
 * @since 2.0
 */
public static void copyURLToFile(final URL source, final File destination,
                 final int connectionTimeout, final int readTimeout) throws IOException {
  final URLConnection connection = source.openConnection();
  connection.setConnectTimeout(connectionTimeout);
  connection.setReadTimeout(readTimeout);
  copyInputStreamToFile(connection.getInputStream(), destination);
}

代码示例来源:origin: lingochamp/okdownload

void configUrlConnection() throws IOException {
  Util.d(TAG, "config connection for " + url);
  if (configuration != null && configuration.proxy != null) {
    connection = url.openConnection(configuration.proxy);
  } else {
    connection = url.openConnection();
  }
  if (configuration != null) {
    if (configuration.readTimeout != null) {
      connection.setReadTimeout(configuration.readTimeout);
    }
    if (configuration.connectTimeout != null) {
      connection.setConnectTimeout(configuration.connectTimeout);
    }
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Returns all the text at the given URL.
 */
public static String slurpURL(URL u, String encoding) throws IOException {
 String lineSeparator = System.lineSeparator();
 URLConnection uc = u.openConnection();
 uc.setReadTimeout(30000);
 InputStream is;
 try {
  is = uc.getInputStream();
 } catch (SocketTimeoutException e) {
  logger.error("Socket time out; returning empty string.");
  logger.err(throwableToStackTrace(e));
  return "";
 }
 try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) {
  StringBuilder buff = new StringBuilder(SLURP_BUFFER_SIZE); // make biggish
  for (String temp; (temp = br.readLine()) != null; ) {
   buff.append(temp);
   buff.append(lineSeparator);
  }
  return buff.toString();
 }
}

代码示例来源:origin: stackoverflow.com

URLConnection conn = url.openConnection();  
conn.setConnectTimeout(timeoutMs);  
conn.setReadTimeout(timeoutMs);  
in = conn.getInputStream();

代码示例来源:origin: TEAMMATES/teammates

@SuppressWarnings("PMD.AssignmentInOperand") // necessary for reading stream response
private static String readResponse(URLConnection conn) throws IOException {
  conn.setReadTimeout(10000);
  StringBuilder sb = new StringBuilder();
  try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), Const.SystemParams.ENCODING);
      BufferedReader rd = new BufferedReader(isr)) {
    String line;
    while ((line = rd.readLine()) != null) {
      sb.append(line);
    }
  }
  return sb.toString();
}

代码示例来源:origin: lingochamp/okdownload

@Test
public void construct_noConfiguration_noAssigned() throws IOException {
  DownloadUrlConnection.Factory factory = new DownloadUrlConnection.Factory();
  factory.create("https://jacksgong.com");
  verify(urlConnection, never()).setConnectTimeout(anyInt());
  verify(urlConnection, never()).setReadTimeout(anyInt());
}

代码示例来源:origin: Netflix/servo

@Override
 public InputStream fetchStatus() throws IOException {
  final URLConnection con = url.openConnection();
  con.setConnectTimeout(1000);
  con.setReadTimeout(2000);
  return con.getInputStream();
 }
}

代码示例来源:origin: javamelody/javamelody

/**
 * Ouvre la connection http.
 * @return Object
 * @throws IOException   Exception de communication
 */
private URLConnection openConnection() throws IOException {
  final URLConnection connection = url.openConnection();
  connection.setUseCaches(false);
  if (CONNECTION_TIMEOUT > 0) {
    connection.setConnectTimeout(CONNECTION_TIMEOUT);
  }
  if (READ_TIMEOUT > 0) {
    connection.setReadTimeout(READ_TIMEOUT);
  }
  // grâce à cette propriété, l'application retournera un flux compressé si la taille
  // dépasse x Ko
  connection.setRequestProperty("Accept-Encoding", "gzip");
  if (headers != null) {
    for (final Map.Entry<String, String> entry : headers.entrySet()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }
  }
  if (url.getUserInfo() != null) {
    final String authorization = Base64Coder.encodeString(url.getUserInfo());
    connection.setRequestProperty("Authorization", "Basic " + authorization);
  }
  return connection;
}

代码示例来源:origin: stackoverflow.com

/**
 * Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in 
 * the 200-399 range.
 * @param url The HTTP URL to be pinged.
 * @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
 * given timeout, otherwise <code>false</code>.
 */
public static boolean pingURL(String url, int timeout) {
  url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

  try {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);
    connection.setRequestMethod("HEAD");
    int responseCode = connection.getResponseCode();
    return (200 <= responseCode && responseCode <= 399);
  } catch (IOException exception) {
    return false;
  }
}

代码示例来源:origin: lingochamp/FileDownloader

@Test
public void construct_validConfiguration_Assigned() throws IOException {
  FileDownloadUrlConnection.Creator creator = new FileDownloadUrlConnection.Creator(
      new FileDownloadUrlConnection.Configuration()
          .proxy(mProxy)
          .connectTimeout(1001)
          .readTimeout(1002)
  );
  creator.create(mURL);
  verify(mURL).openConnection(mProxy);
  verify(mConnection).setConnectTimeout(1001);
  verify(mConnection).setReadTimeout(1002);
}

代码示例来源:origin: stackoverflow.com

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

Uri.Builder builder = new Uri.Builder()
    .appendQueryParameter("firstParam", paramValue1)
    .appendQueryParameter("secondParam", paramValue2)
    .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
      new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();

conn.connect();

代码示例来源:origin: lingochamp/okdownload

@Test
public void construct_validConfiguration_Assigned() throws IOException {
  DownloadUrlConnection.Factory factory = new DownloadUrlConnection.Factory(
      new DownloadUrlConnection.Configuration()
          .proxy(proxy)
          .connectTimeout(123)
          .readTimeout(456)
  );
  factory.create(url);
  verify(url).openConnection(proxy);
  verify(urlConnection).setConnectTimeout(123);
  verify(urlConnection).setReadTimeout(456);
}

相关文章

URLConnection类方法