For some reason when I make a GET request, it seems to go into an infinite loop. I thought it was my web app having an issue, but after trying google.com, the same results occur.
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. 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. 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 ..
try somehhing like
for (; (line =reader.readLine()) != null;) {
}
or
while ((line = br.readLine()) != null) {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.