【发布时间】:2017-09-25 05:18:47
【问题描述】:
我在从远程网络资源读取文本和二进制内容时使用HttpURLConnection 建立连接。
我需要实施考虑到可能存在的问题的方法
- 连接到远程 Web 资源期间的连接超时 和
- 从远程 Web 资源下载内容期间。
URLConnection 类中有 2 个设置器 setConnectTimeout() 和 setReadTimeout() 用于这些目的。
当我在控制台中的计算机上运行下面给出的代码并实现这两个设置器时,一切正常。
由于 81 端口被我的防火墙关闭,我使用 URL 规范为“www.google.com:81”来模拟计算机上的连接超时问题。
按预期在 10 秒后引发异常,并显示在我的控制台中。
然后我通过警告用户连接到远程 Web 资源可能出现问题来处理此异常。
但是当我在 Android 平台下使用超时设置器调用相同的方法时,10 秒后不会引发超时异常。
我搜索了所有StackOverflow,发现在Android下使用超时时遇到类似问题的描述。
但没有一个给出的答案指向问题的具体决定。
谁能指出确切的解决方案如何使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());
}
}
【问题讨论】:
-
你有any异常吗? NB 请去掉粗体字。它没有帮助。
-
是的。大约 40 秒后出现异常(异常:无法解析主机“www.google.com”:没有与主机名关联的地址)
-
你试过用安卓设备上的chrome导航器加载相同的url吗?
-
@Inessa:考虑到您上面的评论,您的 DNS 似乎无法解析主机名,这意味着它无法获取与域名关联的 IP 地址。
-
没有。 android 设备上的 chrome navigator 不提供测试 url。
标签: java android httpurlconnection