在从远程web资源读取文本和二进制内容时,我使用HttpURLConnection
建立连接。
我需要实现考虑到可能存在的问题的方法
有两个设置器( setConnectTimeout()
和setReadTimeout()
of URLConnection
类)用于这些目的。
当我在控制台上运行这两个设置器的实现的代码时,一切都很好。
由于我的防火墙关闭了81个端口,所以我使用URL规范作为"www.google.com:81“来模拟我的计算机上的连接超时问题。
异常按预期在10秒后引发,并显示在我的控制台中。
然后,我通过警告用户与远程web资源的连接可能出现的问题来处理此异常。
但是,当我在Android平台下使用超时设置器调用相同的方法时,超时异常不会在10秒后引发。
我已经搜索了所有的StackOverflow,并找到了类似问题的描述,在安卓下使用超时。
但是,给出的任何答案都不能说明问题的具体决定。
有人能指出确切的解决方案吗?如何使setConnectTimeout()
和setReadTimeout()
设置器在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());
}
}
发布于 2017-09-24 21:29:09
setConnectTimeout(int超时值)如果服务器不可靠,并且您只想等待15秒,然后告诉用户“出了问题”。
setReadTimeout(SetReadTimeout)是当您有连接时,您在read()上被阻塞的超时,如果读取阻塞的时间超过超时,您希望得到一个异常
https://stackoverflow.com/questions/46398049
复制相似问题