使用HttpURLConnection发送带有PUT请求的文件

时间:2012-07-10 19:59:12

标签: java http io httpurlconnection

我正在尝试做一些相对简单的事情。我需要在正文中创建一个简单的PUT请求,以便将文件上传到不在我控制范围内的服务器。这是我到目前为止的代码:

connection = ((HttpURLConnection)new URL(ticket.getEndpoint()).openConnection());
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "video/mp4");
connection.setRequestProperty("Content-Length", String.valueOf(getStreamFile().length()));
connection.setUseCaches(false);
connection.setDoOutput(true);

connection.connect();

outputStream = connection.getOutputStream();

streamFileInputStream = new FileInputStream(getStreamFile());
streamFileBufferedInputStream = new BufferedInputStream(streamFileInputStream);

byte[] streamFileBytes = new byte[getBufferLength()];
int bytesRead = 0;
int totalBytesRead = 0;

while ((bytesRead = streamFileBufferedInputStream.read(streamFileBytes)) > 0) {
    outputStream.write(streamFileBytes, 0, bytesRead);
    outputStream.flush();

    totalBytesRead += bytesRead;

    notifyListenersOnProgress((double)totalBytesRead / (double)getStreamFile().length());
}

outputStream.close();

logger.debug("Wrote {} bytes of {}, ratio: {}", 
        new Object[]{totalBytesRead, getStreamFile().length(), 
            (double)totalBytesRead / (double)getStreamFile().length()});

我正在看我的网络管理员,并且没有发送任何接近我的文件大小的内容。事实上,我不知道是否有任何发送,但我没有看到任何错误。

我需要能够发送此请求并同步测量上传状态,以便能够通知我的听众上传进度。如何将现有示例修改为just work™?

1 个答案:

答案 0 :(得分:2)

尝试将content-type参数设置为multipart/form-dataW3C forms