3

我是 Java 新手,在使用 HTTPURLConnection 在 Android 上发送多个发布请求时遇到了上述错误。我编写了一个 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

请让我知道如何编写这门课。

谢谢!

4

2 回答 2

0

您的实现HTTPUrlConnection 不允许您以这种方式重用连接。我相信您必须使用 anHttpConnectionManager才能以您想要的方式使用 Keep-Alive。

于 2011-01-12T21:32:13.737 回答
0

您需要为每个请求使用一个新的 HttpURLConnection。TCP 连接本身将在幕后进行池化。不要试图自己这样做。

于 2015-08-16T01:21:48.060 回答