簡體   English   中英

HTTPUrlConnection錯誤(從inputStream讀取后無法打開OutputStream)

[英]HTTPUrlConnection error (Can't open OutputStream after reading from an inputStream)

我是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:從inputStream讀取后無法打開OutputStream

請讓我知道如何寫這門課。

謝謝!

您需要為每個請求使用新的HttpURLConnection。 TCP連接本身將在后台匯集。 不要試圖自己這樣做。

您的HTTPUrlConnection實現不允許您以這種方式重用連接 我相信你必須使用HttpConnectionManager以你想要的方式使用Keep-Alive。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM