gpt4 book ai didi

java - 使用 HTTPUrlConnection 时出现 StackOverflowError

转载 作者:行者123 更新时间:2023-12-01 22:05:46 24 4
gpt4 key购买 nike

我在使用 HTTPUrlConnection 时遇到一些问题。该代码基本上在循环中运行,每次连接到不同的 URL,检查响应,如果响应满足某些条件则退出。我收到 StackOverflowError,但我不确定我搞砸了什么。我尝试不使用 connection.disconnect() 但无济于事。

另外,你们对加快下面的代码有什么建议吗?

谢谢

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;
}
}
}

最佳答案

StackOverflowError 表示您的 sendRequest 递归方法调用已被频繁发送,并且堆栈上没有剩余内存。有关详细解释,请参阅 What is a StackOverflowError?首先,您应该检查一下破坏外观的地方(在 handleResponsesendRequest 中)是否完全按照您的预期工作。尤其是在 handleResponse 中> 看起来是有线的。如果一切正常,您可以尝试重写逻辑以使用循环而不是递归调用。

关于java - 使用 HTTPUrlConnection 时出现 StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32842085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com