[英]android http get request infinite loop
For some reason when I make a GET request, it seems to go into an infinite loop. 出于某种原因,当我发出GET请求时,它似乎进入了一个无限循环。 I thought it was my web app having an issue, but after trying google.com, the same results occur.
我认为这是我的网络应用程序有问题,但在尝试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());
}
this code never passes the for loop. 此代码永远不会传递for循环。 It just continues printing.
它只是继续打印。 Anyone see what's wrong?
有谁看到了什么问题?
The problem is here 问题出在这里
for (String line = reader.readLine(); line != null;) {
System.out.println(line);
}
"line" is always the first line of the input. “line”始终是输入的第一行。 You need to read new lines.
你需要读新行。
line = reader.readLine() shuold call every time when loop runs but in your code in runs once only as it is the part of initialization part .. line = reader.readLine()shuold每次循环运行时调用,但在代码中只运行一次,因为它是初始化部分的一部分。
try somehhing like 试着像
for (; (line =reader.readLine()) != null;) {
}
or
while ((line = br.readLine()) != null) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.