gpt4 book ai didi

java - 读取输入后无法写入输出;经历过这种情况但不确定原因

转载 作者:行者123 更新时间:2023-12-01 09:12:09 25 4
gpt4 key购买 nike

我正在经历this问题虽然不确定是否准确。

我发现日志中读取输入后无法写入输出,并且根据上述内容,我相信发生这种情况是因为 getResponseCode() 后跟 >getOutputStream().

这是否是我看到的记录错误的原因?

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

if(conn.getResponseCode() == 0){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());

最佳答案

以下代码

StringWriter writer = new StringWriter();

String pushURL = "Your URL";

URL url = new URL(pushURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("Content-Type", "application/restService");

conn.setConnectTimeout(30000);

conn.setReadTimeout(30000);

if(conn.getResponseCode() == 0){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}

String input = writer.getBuffer().toString();

OutputStream os = conn.getOutputStream();

os.write(input.getBytes());

os.flush();

由于以下位置 here 将导致 java.net.ProtocolException :

The HTTP protocol is based on a request-response pattern: you send your request first and the server responds. Once the server responded, you can't send any more content, it wouldn't make sense. (How could the server give you a response code before it knows what is it you're trying to send?)

So when you call server.getResponseCode(), you effectively tell the server that your request has finished and it can process it. If you want to send more data, you have to start a new request.

因此,OP 在 conn.getResponseCode() 之后调用 conn.getOutputStream();,生成 java.net.ProtocolException > 其 Exception.getMessages() 产生

Cannot write output after reading input

关于java - 读取输入后无法写入输出;经历过这种情况但不确定原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40852262/

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