HTTPUrlConnection错误(在读取输入流后无法打开输出流)

3

我是Java的新手,在使用HTTPURLConnection在Android上发送多个POST请求时遇到了上述错误。我编写了一个HTTPTransport类,希望其中有sendMessage和recvMessage方法。

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: can't open OutputStream after reading from an inputStream

请告诉我如何编写这个类。

谢谢!

2个回答

0

每个请求都需要使用一个新的HttpURLConnection。TCP连接本身将在后台进行池化。不要尝试自己处理。


0

非常抱歉,由于我对Java非常陌生,我没有理解你的回复。 - smitten
这个有帮助吗?http://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html - dkarp
谢谢,我会仔细阅读它。 - smitten
我从这份文档中得到的信息是,关闭输入流可以提高使HTTP连接持久化的机会。我认为我已经做到了。 - smitten
我暂时改用HTTPClient了。目前看来它似乎可以正常工作。 - smitten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接