0

我遇到了这个问题,但不确定是否准确。

Cannot write output after reading input在日志中发现,根据上述内容,我相信这是因为 agetResponseCode()后面跟着 a 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());
4

1 回答 1

1

以下代码

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();

将导致 ajava.net.ProtocolException由于位于此处的以下内容:

HTTP 协议基于请求-响应模式:您首先发送请求,然后服务器响应。一旦服务器响应,您就不能再发送任何内容,这没有任何意义。(服务器如何在知道您要发送的内容之前给您响应代码?)

因此,当您调用 server.getResponseCode() 时,您有效地告诉服务器您的请求已经完成并且它可以处理它。如果你想发送更多数据,你必须开始一个新的请求。

因此,OP 正在调用conn.getOutputStream();conn.getResponseCode()然后生成java.net.ProtocolExceptionException.getMessages()产量

读取输入后无法写入输出

于 2016-11-29T11:25:28.210 回答