5

我正在测试一个代码示例,但它总是错误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

4

4 回答 4

1
  1. 您必须在将输入流读取到流末尾后关闭它。

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

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

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

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

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

于 2016-07-05T01:57:57.350 回答
0

移动

connection.connect();

connection.setRequestMethod("POST");
于 2014-01-19T03:53:37.657 回答
0

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

最重要的是,对于 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();
}
于 2014-12-02T11:19:00.210 回答
-1

添加

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

connection = (HttpsURLConnection) url.openConnection();

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

于 2016-12-04T04:31:19.280 回答