【问题标题】:Android: java.lang.IllegalStateException: Already connectedAndroid:java.lang.IllegalStateException:已经连接
【发布时间】:2014-01-19 02:57:49
【问题描述】:

我正在测试一个代码示例,但它总是在 connection.setDoInput(true); 出现错误

HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;

String urlServer = "https://www.myurl.com/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

int bytesRead = 0;
int bytesAvailable = 0;
int bufferSize = 0;
byte[] buffer = null;
int maxBufferSize = 1*1024*1024;

try {
    FileInputStream fileInputStream = new FileInputStream(new File(params[0]));

    URL url = new URL(urlServer);

    connection = (HttpsURLConnection) url.openConnection();
    connection.setConnectTimeout(1000);

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    connection.setConnectTimeout(1000);

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + params[0] + "\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

错误日志是java.lang.IllegalStateException: Already connected。 我已经尝试了这些,但没有一个有效:

connection.setRequestProperty("Connection", "close");
connection.disconnect();
connection.setConnectTimeout(1000);

编辑:即使我没有打电话给connection.connect(),它仍然给出同样的错误already connected

【问题讨论】:

  • OutputStreamWriterInputStreamReader在使用后是否关闭了?
  • 是的。并且错误发生在使用OutputStreamWriter和InputStreamReader这行之前。
  • @downvoter:为什么它被否决了?我已经阅读并尝试了其他类似的问题,但没有一个有效,这就是我发布这个的原因。
  • 因为你没有发布堆栈跟踪?

标签: java android httpsurlconnection


【解决方案1】:
  1. 您必须在将输入流读取到流末尾后关闭它。

  2. 您应该删除connect() 的调用。你把它放错地方了,但它是自动的,根本不需要调用。

  3. 您还可以删除设置 POST 的行。这在调用 setDoOutput(true) 时是隐含的。

  4. 您还可以删除复制循环中的大部分杂物。使用固定大小的缓冲区:

    while ((count = in.read(buffer)) > 0)
    {
        out.write(buffer, 0, count);
    }
    

    每次读取不要使用新的缓冲区;不要打电话给available();不通过 GO;不要收取 200 美元。

【讨论】:

    【解决方案2】:

    移动

    connection.connect();
    

    之后

    connection.setRequestMethod("POST");
    

    【讨论】:

      【解决方案3】:

      有一篇关于http连接的很好的帖子here

      底线是,对于 POST,您只需要以下内容。

      HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
      // setDoOutput(true) implicitly set's the request type to POST
      connection.setDoOutput(true);
      

      我也不确定您是否需要指定 HttpsURLConnection。您可以使用 HttpURLConnection 连接到 Https 站点。让 java 在幕后为您完成工作。

      这是我用于 json 帖子的 POST 代码

      public static String doPostSync(final String urlToRead, final String content) throws IOException {
          final String charset = "UTF-8";
          // Create the connection
          HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
          // setDoOutput(true) implicitly set's the request type to POST
          connection.setDoOutput(true);
          connection.setRequestProperty("Accept-Charset", charset);
          connection.setRequestProperty("Content-type", "application/json");
      
          // Write to the connection
          OutputStream output = connection.getOutputStream();
          output.write(content.getBytes(charset));
          output.close();
      
          // Check the error stream first, if this is null then there have been no issues with the request
          InputStream inputStream = connection.getErrorStream();
          if (inputStream == null)
              inputStream = connection.getInputStream();
      
          // Read everything from our stream
          BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, charset));
      
          String inputLine;
          StringBuffer response = new StringBuffer();
      
          while ((inputLine = responseReader.readLine()) != null) {
              response.append(inputLine);
          }
          responseReader.close();
      
          return response.toString();
      }
      

      【讨论】:

        【解决方案4】:

        添加

        if (connection != null) connection.disconnect();
        

        之前

        connection = (HttpsURLConnection) url.openConnection();
        

        看看问题是否解决了。如果是,则表示您的原始代码中未调用 connection.disconnect()。也许您将connection.disconnect() 放在try 块的末尾,但是在它之前发生异常,因此它会跳转到catch 块并且永远不会调用connection.disconnect()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-19
          • 1970-01-01
          • 1970-01-01
          • 2020-03-27
          • 1970-01-01
          • 1970-01-01
          • 2017-05-27
          • 2017-02-17
          相关资源
          最近更新 更多