Closed
Description
最近做的一个项目用到protobuf,使用dio发送的post请求数据为Uint8List
格式:
UserMeRequest req = UserMeRequest.create();
req.token = await Storage.getToken();
Uint8List reqBuffer = req.writeToBuffer();
Uint8List responseBuffer = await dio.post('user/me', data: reqBuffer); // <------
UserMeResponse resp = UserMeResponse.fromBuffer(responseBuffer);
print('$resp <<<<<<<<<<<<<<userMe');
服务端总提示protobuf数据格式不正确,跟踪代码我发现dio转换器总是返回String格式:
DefaultTransformer
返回的数据将data转化为String类型。
Future<String> transformRequest(RequestOptions options) async {
var data = options.data ?? "";
if (data is! String) {
if (options.contentType.mimeType == ContentType.json.mimeType) {
return json.encode(options.data);
} else if (data is Map) {
return Transformer.urlEncodeMap(data);
}
}
return data.toString(); /// <=================== 调用了data.toString()方法
}
这样会导致服务端处理的时候将接收的字节数组按照字符串处理,导致格式无法识别。
建议:
能否添加Uint8List格式的判断,不做处理直接返回data,
像这样:
Future<dynamic> transformRequest(RequestOptions options) async {
var data = options.data ?? "";
if (data is! String) {
if (options.contentType.mimeType == ContentType.json.mimeType) {
return json.encode(options.data);
} else if (data is Map) {
return Transformer.urlEncodeMap(data);
} else if (data is Uint8List) { /// <========= 添加Uint8List格式判断条件
return data;
}
}
return data.toString();
}
Activity
jianzi0307 commentedon Jul 9, 2019
nextwhale commentedon Nov 14, 2020
You can create a method to transform proto buffer to Stream like this:
The usage example: