【问题标题】:How to write type adapter for GSON to send stream?如何为 GSON 编写类型适配器以发送流?
【发布时间】:2013-08-20 11:52:51
【问题描述】:

我班级的一个字段是文件名。 对于序列化,我将编写Gson 类型适配器(实现JsonSerializer<MyClass>),它应该发送文件流。

问题是我不希望它读取所有文件数据(流)并将其作为字符串保存在内存中,因为内存大小是有限的(它是移动设备),我必须发送一些其他字段(@987654323 @ f.e. 下面),所以 json 应该是这样的:

data:
{
    filename:"filename.png"
    filedata:"(base64 file data stream here)"
}

在这种情况下,在网络中将文件数据作为字段发送的最佳方式是什么?

PS。如果有帮助,网络发送由 Apache Http Client 完成

【问题讨论】:

    标签: json adapter gson


    【解决方案1】:

    在一个请求正文中混合 json 和大型二进制数据似乎不是一个好的架构解决方案。可以改用 http Multipart:

        HttpPost request = new HttpPost(url);
    
        MultipartEntity multipartEntity = new MultipartEntity();
        request.setEntity(multipartEntity);
    
        // body
        try {
            multipartEntity.addPart("json", new StringBody(body, "application/json", Charset.forName("utf-8")));
        } catch (UnsupportedEncodingException e) {
            throw new ResourceLoadingException(e);
        }
    
        // files
        for (int i=0; i<filespaths.size(); i++) {
            String eachFilePath = filespaths.get(i);
            File file = new File(eachFilePath);
            multipartEntity.addPart("file" + String.valueOf(i), new FileBody(file));
        }
    

    Android 不支持 Multipart body 但您可以轻松添加对它的支持(如果使用 Maven 或 Gradle)的移动设备:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.2.5</version>
    </dependency>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      相关资源
      最近更新 更多