2016-11-28 35 views
0

我遇到了this问题,虽然不确定是否确切。读取输入后无法写入输出;出现这种情况,但不是肯定的原因

我在日志中发现了Cannot write output after reading input,根据上述情况,我认为这是因为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()); 
+0

哪里是你的代码后,无法写入输出?你可以在引发这个错误的行上发布一段代码吗? –

回答

0

下面的代码

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

将导致java.net.ProtocolException因为以下位于here

HTTP协议是基于请求 - 响应模式:你把你的首先请求并且服务器响应。一旦服务器响应,你不能发送更多的内容,这是没有道理的。 (在服务器知道你要发送的内容之前,服务器怎么能给你一个响应代码?)

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

因此,OP呼吁conn.getResponseCode()conn.getOutputStream();这是产生java.net.ProtocolExceptionException.getMessages()产量

读取输入