在单个连接中发送多个 post 请求的 HttpUrlConnection

HttpUrlConnection that sends multiple post request in single connection

我想在单个 HTTP 连接中进行多次 post 调用,

  1. 我将发送 Arraylist<String>httpConnection 对象作为输入参数。
  2. 迭代ArrayList并将请求写入服务器。

我最终收到以下错误:

Cannot write output after reading input.
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)

这是我的代码。我正在使用来完成上述任务。

public boolean sendToLogsAPI(ArrayList<String> logList, HttpURLConnection conn) throws IOException
{
    try 
    {
         DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
         for(int i=0; i<logList.size(); i++)
         {
             wr = new DataOutputStream(conn.getOutputStream());
             wr.writeBytes(logList.get(i));
             wr.flush();
             int nothing = conn.getResponseCode();
             String morenothing = conn.getResponseMessage();
         }   
         wr.flush();
         wr.close();
    }
    catch (Exception e) 
    {
      e.printStackTrace();
    } 
    finally 
    {
      if(conn != null) 
      {
        conn.disconnect(); 
      }
    }

    return false;
}

我该如何克服这种情况?

您正在关闭此方法中的连接,因此您不能使用相同的方法调用它两次 HttpURLConnection conn

您可能不应该在此处断开连接 conn.disconnect();,而应将其留给来电者。

根据 HttpURLConnection 的 javadoc:

Each HttpURLConnection instance is used to make a single request

有关详细信息,请参阅 this

问题是一旦完成 wr.flush(),您就无法再执行 conn.getOutputStream()

如果您想发送另一个 post 请求,您必须创建一个新的 HttpURLConnection 实例。您可以通过多种方式做到这一点。一种方法是创建一个方法 getHttpURLConnection(),它每次都提供新的连接 [如果你展示了 HttpURLConnection 的实例是如何创建的,它被传递给方法 sendToLogsAPI(),那么我可以告诉你getHttpURLConnection() 的实现。] 并修改现有代码如下:

public boolean sendToLogsAPI(ArrayList<String> logList) throws IOException
{
    DataOutputStream wr = null;
    HttpURLConnection conn = null;

    try 
    {
         for(int i=0; i<logList.size(); i++)
         {
             conn = conn("<Some-URL>","<API-Key>","<GUID>");
             wr = new DataOutputStream(conn.getOutputStream());
             wr.writeBytes(logList.get(i));
             wr.flush();
             int nothing = conn.getResponseCode();
             String morenothing = conn.getResponseMessage();
         }   
         if(wr != null) {
             wr.close();
         }
    }
    catch (Exception e) 
    {
      e.printStackTrace();
    } 
    finally 
    {
      if(conn != null) 
      {
        conn.disconnect(); 
      }
    }

    return false;
}

我想问你的另一个问题是为什么要使用相同的 HttpURLConnection 实例。即使您使用其中的多个,也可以使用相同的 Socket(和底层 TCP)。所以不用担心 HttpURLConnection.

的多个实例