One of the fields of my class is filename. For serialization i'm going to write Gson type adapter (implements JsonSerializer<MyClass>
) which should send file stream.
我的类的一个字段是文件名。对于序列化,我将编写Gson类型适配器(实现JsonSerializer
The problem is that i don't want it to read all file data (stream) and hold it as string in the memory as memory size is limited (it's mobile device) and i have to send some another fields (filename
f.e. below), so json should look like:
问题是,我不希望它读取所有的文件数据(流),并把它作为内存中的字符串保存,因为内存大小是有限的(它是移动设备),并且我必须发送一些其他字段(文件名f.e. e),所以json应该是这样的:
data:
{
filename:"filename.png"
filedata:"(base64 file data stream here)"
}
What is the best way to send file data in network as a field in this case?
在这种情况下,将网络中的文件数据作为字段发送的最佳方式是什么?
PS. Network sending is done by Apache Http Client if it helps
网络发送是由Apache Http客户端完成的,如果它有帮助的话。
1 个解决方案
#1
1
It seems that it's not good architectural solution to mix json and large binary data within one request body. One can use http Multipart instead:
在一个请求体中混合json和大型二进制数据似乎不是很好的架构解决方案。可以使用http多部分代替:
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));
}
What about mobile devices Android does not support Multipart bodies but you can add support for it easily (if using Maven or Gradle):
那么移动设备呢? Android不支持多部分主体,但是你可以很容易地添加对多部分主体的支持(如果使用Maven或Gradle):
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.2.5</version>
</dependency>
#1
1
It seems that it's not good architectural solution to mix json and large binary data within one request body. One can use http Multipart instead:
在一个请求体中混合json和大型二进制数据似乎不是很好的架构解决方案。可以使用http多部分代替:
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));
}
What about mobile devices Android does not support Multipart bodies but you can add support for it easily (if using Maven or Gradle):
那么移动设备呢? Android不支持多部分主体,但是你可以很容易地添加对多部分主体的支持(如果使用Maven或Gradle):
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.2.5</version>
</dependency>