我正在开发一个Android应用程序,它将采取网页的源代码,然后解析它。Android设备无法连接到网页与HttpURLConnection
只要我的设备连接到它开发的电脑上,我就可以得到这个工作,但是,当我试图从pc断开连接时,它似乎无法检索信息。有人可以告诉我我做错了什么吗?
要通过的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()' – 2013-04-11 09:21:27
@Haelty我是否需要关闭和我一样的连接?我试图在发布模式下运行它,但手机不会连接。 – Nick 2013-04-11 09:46:16
是的,最好关闭连接;)但是你可以在'finally'块中调用它,以便在任何情况下调用它(即使之前调用了“return”)。 – 2013-04-11 09:49:29