【问题标题】:HTTPUrlConnection error (Can't open OutputStream after reading from an inputStream)HTTPUrlConnection 错误(从 inputStream 读取后无法打开 OutputStream)
【发布时间】:2015-08-16 09:21:48
【问题描述】:

我是 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

请告诉我如何编写这门课。

谢谢!

【问题讨论】:

    标签: java exception protocols httpurlconnection


    【解决方案1】:

    您对HTTPUrlConnection does not allow you to reuse the connection in this manner 的实现。我相信您必须使用 HttpConnectionManager 才能以您想要的方式使用 Keep-Alive。

    【讨论】:

    • 很抱歉,由于我是 Java 新手,所以我不明白您的回复。
    • 谢谢,我会处理的。
    • 我从这个文档中得到的只是应该关闭输入流以改进使 HTTP 连接持久化的更改。我想我已经在这样做了。
    • 我现在改用 HTTPClient。到目前为止,它似乎工作正常。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2012-09-10
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      相关资源
      最近更新 更多