【发布时间】:2013-04-11 19:10:50
【问题描述】:
我正在开发一个 android 应用程序,它会从网页中获取源代码,然后对其进行解析。
只要我的设备连接到开发它的电脑,我就能让它工作,但是,当我尝试在与电脑断开连接的情况下运行它时,它似乎无法检索信息。有人可以告诉我我做错了什么吗?
为了获取源代码,我通过 AsyncTask 使用以下代码:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000 /* milliseconds */);
conn.setConnectTimeout(25000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
if (response == 200) {
is = conn.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));
// Convert the InputStream into a string
String s = "";
while ((s = buffer.readLine()) != null) {
myTextView.append(s);
myTextView.append("\n");
}
conn.disconnect();
is.close();
return myTextView.getText().toString();
} else {
conn.disconnect();
return "";
}
} finally {
if (is != null) {
is.close();
}
}
}
【问题讨论】:
-
不知道它是否会有所帮助,但是一旦您致电
openConnection(),您就不必致电connect() -
@Haelty 我需要像以前那样关闭连接吗?我也尝试在发布模式下运行它,但是手机无法建立连接。
-
是的,最好关闭连接;)但是您可以在
finally块中调用它,以便在任何情况下都会调用它(即使之前调用了return)。 -
@Haelty 不,我不能,因为 conn 是在 try 块中定义的
-
你是对的。所以保持原样。但是会发生什么?它会抛出异常还是返回空字符串?响应码是什么?
标签: android android-asynctask httpurlconnection