我正在尝试做一些非常简单的事情,但到目前为止,我一直试图尝试各种方法来实现它。我尝试使用简单java.io.Socket
上传到使用java.io.HttpURLConnection
的网址,最后使用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.
我需要将文件的字节(可能来自FileInputStream
)写入包含视频字节的主请求主体。
我基本上有两个要求:
如何在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
例外而失败。
答案 0 :(得分:0)
对于1,您需要使用multipart request。推荐的帖子描述了它。对于2,在发送数据时使用一些counting stream包装器。计数流可能需要挂钩在HttpClient中。
如果您为不适合自己的内容添加更多详细信息,则可以提供更多详细信息。