[英]android http get request infinite loop
出於某種原因,當我發出GET請求時,它似乎進入了一個無限循環。 我認為這是我的網絡應用程序有問題,但在嘗試google.com后,會出現相同的結果。
try {
URL url = new URL("http://google.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000 /* milliseconds */);
con.setConnectTimeout(15000 /* milliseconds */);
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
InputStream is = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
for (String line = reader.readLine(); line != null;) {
System.out.println(line);
}
reader.close();
} catch (ClientProtocolException e) {
System.out.println("Client Exception " + e.getMessage());
} catch(IOException e) {
e.printStackTrace();
System.out.println("IOException " + e.getMessage());
}
此代碼永遠不會傳遞for循環。 它只是繼續打印。 有誰看到了什么問題?
問題出在這里
for (String line = reader.readLine(); line != null;) {
System.out.println(line);
}
“line”始終是輸入的第一行。 你需要讀新行。
line = reader.readLine()shuold每次循環運行時調用,但在代碼中只運行一次,因為它是初始化部分的一部分。
試着像
for (; (line =reader.readLine()) != null;) {
}
or
while ((line = br.readLine()) != null) {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.