我在从远程 Web 资源读取文本和二进制内容时使用 HttpURLConnection
建立连接。
我需要实现考虑可能出现的问题的方法
- 连接远程 Web 资源期间连接超时 和
- 从远程网络资源下载内容期间。
URLConnection
类有 2 个 setter setConnectTimeout()
和 setReadTimeout()
用于这些目的。
当我在控制台中的计算机上运行下面给出的代码并实现这两个 setter 时,一切正常。
我使用 URL 规范“www.google.com:81”来模拟计算机上的连接超时问题,因为 81 端口被我的防火墙关闭。
异常在 10 秒后按预期引发,并显示在我的控制台中。
然后,我通过警告用户连接远程 Web 资源时可能出现的问题来处理此异常。
但是当我在 Android 平台下使用超时 setter 调用相同的方法时,10 秒后不会引发超时异常。
我搜索了所有 StackOverflow 并找到了在 Android 下使用超时时出现类似问题的描述。
但是给出的答案都没有指向问题的具体决定。
任何人都可以指出如何使 setConnectTimeout()
和 setReadTimeout()
setter 在 Android 下按这些代码行的预期工作的确切解决方案吗?
package com.downloader;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebDownloader
{
public static String StringFileContent;
public static boolean StringFileIsDownloaded;
public static byte[] BinaryFileContent;
public static boolean BinaryFileIsDownloaded;
public static void readStringFileContent(String urlString)
{
StringFileContent = "";
StringFileIsDownloaded = false;
try
{
URL Url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)Url.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader in = new BufferedReader(inputStreamReader);
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
StringFileContent = response.toString();
StringFileIsDownloaded = true;
}
catch (Exception localException)
{
System.out.println("Exception: " + localException.getMessage());
}
}
public static void readBinaryFileContent(String urlString)
{
BinaryFileContent = new byte[0];
BinaryFileIsDownloaded = false;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try
{
URL Url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)Url.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
byte[] chunk = new byte['?'];
int bytesRead;
while ((bytesRead = inputStream.read(chunk)) > 0)
{
outputStream.write(chunk, 0, bytesRead);
}
BinaryFileContent = outputStream.toByteArray();
BinaryFileIsDownloaded = true;
}
catch (Exception localException)
{
System.out.println("Exception: " + localException.getMessage());
}
}
最佳答案
setConnectTimeout(int 超时) 如果服务器不可靠,而您只想等待 15 秒,然后告诉用户“出了问题”。
setReadTimeout(int timeout) 是当您有连接时的超时,您在 read() 上被阻塞,并且如果读取阻塞时间超过超时,您希望获得异常
关于java - 如何让HttpURLConnection setConnectTimeout在Android下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46398049/