我正在開發一個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