问题描述
我是Java新手,在使用HTTPURLConnection在Android上发送多个帖子请求时遇到了上述错误。我编写了一个HTTPTransport类,我希望在其中使用sendMessage和recvMessage方法。
I am new to Java and am running into the above mentioned error while using HTTPURLConnection to send multiple post requests on Android. I have written an HTTPTransport class in which I would like to have sendMessage and recvMessage methods.
public class HTTPTransport
{
private HttpURLConnection connection;
public HTTPTransport()
{
URL url = new URL("http://test.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setRequestProperty("Connection", "Keep-Alive");
}
public void sendMessage(byte[] msgBuffer, long size)
{
try
{
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.write(msgBuffer, 0, (int)size);
dos.flush();
dos.close();
dos.close();
}
catch( IOException e )
{
// This exception gets triggered with the message mentioned in the title.
Log.e(TAG, "IOException: " + e.toString());
}
}
public byte[] recvMessage()
{
int readBufLen = 1024;
byte[] buffer = new byte[readBufLen];
int len = 0;
FileOutputStream fos = new FileOutputStream(new File("/sdcard/output.raw"));
DataInputStream dis = new DataInputStream(connection.getInputStream());
while((len = dis.read(buffer, 0, readBufLen)) > 0)
{
Log.d(TAG, "Len of recd bytes " + len + ", Byte 0 = " + buffer[0]);
//Save response to a file
fos.write(buffer, 0, len);
}
fos.close();
dis.close();
return RecdMessage;
}
}
我能够使用sendMessage成功发送第一条消息和recvMessage。当我尝试发送第二个时,我看到了这个错误:
IOException:java.net.ProtocolException:从inputStream读取后无法打开OutputStream
I am able to send the first message successfully using sendMessage and recvMessage. When I try to send the second one, I see this error:IOException: java.net.ProtocolException: can't open OutputStream after reading from an inputStream
请告诉我如何撰写本课程。
Please let me know how I can write this class.
谢谢!
推荐答案
您的 HTTPUrlConnection的实现
。我相信你必须使用 HttpConnectionManager
以你想要的方式使用Keep-Alive。
Your implementation of HTTPUrlConnection
does not allow you to reuse the connection in this manner. I believe you'll have to use an HttpConnectionManager
to make use of Keep-Alive in the manner you want.
这篇关于HTTPUrlConnection错误(从inputStream读取后无法打开OutputStream)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!