I'm having some trouble using HTTPUrlConnection. The code is basically running in a loop, connecting to a different URL each time, checking the response, and quitting if the response meets some criteria. I'm getting StackOverflowError, but I'm not sure what I have messed up. I tried without using connection.disconnect()
but to no avail.
Also, do you guys have any tips on speeding up the code below?
Thanks
Exception in thread "main" java.lang.StackOverflowError at java.security.AccessController.doPrivileged(Native Method) at java.net.Socket.getInputStream(Socket.java:911) at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:642) at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1535) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440) at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) at Main.sendRequest(Main.java:96) at Main.handleResponse(Main.java:140)
public class Main {
static int counter;
public static void main(String [] args) {
counter = 0;
sendRequest("http://192.168.0.1");
}
public static void sendRequest(String path) {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String response = stringBuilder.toString();
handleResponse(response);
inputStreamReader.close();
bufferedReader.close();
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void handleResponse(String response) {
String s = response.substring(62,67);
if (s.equals("Statu")) {
return;
} else {
sendRequest("http://192.168.0.1/" + counter);
counter += 1;
}
}
}