java - 使用 HttpClient 发布 Base64 编码的视频文件

标签 java httpclient apache-commons

我正在尝试使用 HttpClient 将媒体文件发布到服务器。我的代码适用于图像文件,但视频文件(mp4)无法重播。我用于发布文件的代码:

   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(bytes) 进行 Base64 编码;

最佳答案

https://hc.apache.org/httpcomponents-client-4.3.x/examples.html

查看示例 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。

关于java - 使用 HttpClient 发布 Base64 编码的视频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744710/

相关文章:

java - xmlConfig.configurationAt 未获取值

java - JSF:如何在页面上显示 BufferedImage?

Java:不可变到不可变的转换

android - 使用 httpPost 和 httpclient 保存 cookie

android - android中的HttpClient在接收到内容时是否进行内存/磁盘缓存?

java - 在 Java 中从多个字符串构建标记列表的有效方法

java - 连接到 Docker 容器中的 H2 数据库

java - 如何将小数值转换为分数值?

c# - HttpClient 正在发送额外的 cookie

java - 处理来自 apache-commons exec 的输出