2012-07-10 111 views
1

我试图做一些相对简单的事情。我需要使用正文中的文件进行简单的PUT请求,以便将文件上传到不在我控制范围内的服务器。这里是我到目前为止的代码:使用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()}); 

我看我的网络经理和我没有任何文件的大小接近被发送。事实上,我不知道是否有任何东西发送,但我看不到任何错误。

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

回答

2

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

+0

我将视频上传到Vimeo及其[官方上传指南](https://developer.vimeo.com/apis/advanced/upload#streaming-step3)告诉我以这种方式提出请求。 – 2012-07-10 21:32:08

相关问题