我正在尝试做一些非常简单的事情,但到目前为止,我尝试各种方法都没有成功。我尝试使用 simple java.io.Socket
、使用 ajava.io.HttpURLConnection
和最后使用 a上传到 URL org.apache.commons.httpclient.HttpClient
,但每次都未能成功。
我需要提出这样的请求:
PUT http://1.2.3.4:8080/upload?ticket_id=abcdef124567890 HTTP/1.1
Host: 1.2.3.4:8080
Content-Length: 339108
Content-Type: video/mp4
\0abc\32af ... etc.
我需要将文件的字节(可能来自 a FileInputStream
)写入包含视频字节的主请求正文。
我基本上有两个要求:
- 我必须使用 PUT 请求将文件上传到给定的服务器。
- 我必须能够看到上传的进度。
如何在 Java 中实现这一点?
编辑
这是我尝试使用 Apache 执行此操作HttpClient
:
HttpClient httpClient = new HttpClient();
PutMethod httpMethod = new PutMethod(ticket.getEndpoint());
httpMethod.setRequestHeader("Content-Type", "video/mp4");
httpMethod.setRequestHeader("Content-Length", String.valueOf(getStreamFile().length()));
final FileInputStream streamFileInputStream = new FileInputStream(getStreamFile());
final BufferedInputStream bufferedInputStream = new BufferedInputStream(streamFileInputStream);
httpMethod.setRequestEntity(new RequestEntity() {
@Override public void writeRequest(OutputStream out)
throws IOException {
byte[] fileBuffer = new byte[getBufferLength()];
int bytesRead = 0;
int totalBytesRead = 0;
final int totalFileBytes = (int)getStreamFile().length();
while ((bytesRead = bufferedInputStream.read(fileBuffer)) > 0) {
out.write(fileBuffer, 0, bytesRead);
totalBytesRead += bytesRead;
notifyListenersOnProgress((double)totalBytesRead / (double)totalFileBytes);
}
}
@Override public boolean isRepeatable() {
return true;
}
@Override public String getContentType() {
return "video/mp4";
}
@Override public long getContentLength() {
return getStreamFile().length();
}
});
final int responseCode = httpClient.executeMethod(httpMethod);
logger.debug("Server Response {}: {}", responseCode,
httpMethod.getResponseBodyAsString());
这失败了,但有一个java.net.SocketException: Broken pipe
例外。