Java 使用HttpClient发布Base64编码的视频文件
我正在尝试使用HttpClient将媒体文件发布到服务器。我的代码适用于图像文件,但是视频文件(mp4)无法重放。我发布文件的代码:Java 使用HttpClient发布Base64编码的视频文件,java,httpclient,apache-commons,Java,Httpclient,Apache Commons,我正在尝试使用HttpClient将媒体文件发布到服务器。我的代码适用于图像文件,但是视频文件(mp4)无法重放。我发布文件的代码: HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new Ht
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(REMOTE + "/add_file.php");
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
ContentBody cbFile = null;
String mimeType = "";
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")) {
mimeType = "image/jpeg";
} else if (file.getName().endsWith(".mp4")) {
mimeType = "video/mp4";
}
mpEntity.addTextBody("recipient_phone", recipientPhoneStr);
mpEntity.addTextBody("sender_phone", "55000");
mpEntity.addTextBody("sender_key", "my_secret");
mpEntity.addTextBody("file_name", file.getName());
mpEntity.addTextBody("userfile", encodeFileToBase64Binary(file));
httppost.setEntity(mpEntity.build());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (response.getStatusLine().toString().compareTo(HTTP_ERROR) == 0) {
throw new IOException(HTTP_ERROR);
}
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
使用Base64.encodeBase64String(字节)对文件进行Base64编码
查看示例POST程序
使用以下命令将mp4映射到字节,然后将其包装为适当的“实体”类型,以便执行POST
FileInputStream fis = new FileInputStream(mfile);
FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory
int sz = (int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
byte[] data2 = new byte[bb.remaining()];
bb.get(data2);
ByteArrayEntityHC4 reqEntity = new ByteArrayEntityHC4(data2);
httpPost.setEntity(reqEntity);
fis.close();
然后根据POST类型的请求调用exec。您是否已检查是否正确接收了所有字节?您可能达到了php的post_max_大小或apache/nginx限制。谢谢bart。是的,post_max_大小足够了…如何检查apache限制?将文件映射到字节,并将缓冲区包装在post的“byteArrayEntity”中。这是发送视频文件(mp4,mov)的一个很好的解决方案。其他解决方案仅适用于pdf/ppt/text等,但不适用于mp4。