我有 4 天的时间,尝试在 android 中使用 Retrofit 1.8.0 进行多部分请求并取得任何成功。我的界面看起来像这样
@Multipart
@POST("/posts/add.json")
void addComment(
@Part("id") String id,
@Part("post[body]") String body,
@Part("post[attachment]") TypedFile attachment,
Callback<Map<String, String>> callback );
但是,在服务器端,我收到以下信息
Parameters: {"id"=># <File:/var/folders/z0/0ggjvvfj4t1fdsvbxf3lc9pw0000gn/T/RackMultipart9853-0>, "post"=>{"body"=>#<File:/var/folders/z0/0ggjvvfj4t1fdsvbxf3lc9pw0000gn/T/RackMultipart9853-1>, "attachment"=>#<File:/var/folders/z0/0ggjvvfj4t1fdsvbxf3lc9pw0000gn/T/RackMultipart9853-2>}, "controller"=>"posts", "action"=>"add", "format"=>"json"}
如您所见,文件部分在每个部分都发送它,但是我缺少参数的 id 和 post[body] 值
这是 Retrofit 试图发送的内容
02-06 15:01:16.213 32545-822/com.myapp D/Retrofit﹕ --fe41634b-6826-4ee4-95cb-65efb0ca66c2
Content-Disposition: form-data; name="id"
Content-Type: text/plain; charset=UTF-8
Content-Length: 3
Content-Transfer-Encoding: binary
189
--fe41634b-6826-4ee4-95cb-65efb0ca66c2
Content-Disposition: form-data; name="post[body]"
Content-Type: text/plain; charset=UTF-8
Content-Length: 4
Content-Transfer-Encoding: binary
test
--fe41634b-6826-4ee4-95cb-65efb0ca66c2
Content-Disposition: form-data; name="post[attachment]"; filename="IMG_20140203_144358.jpg"
Content-Type: image/jpg
Content-Length: 1615460
Content-Transfer-Encoding: binary
����/�Exif����MM��*���������
这是 HttpMime 库在 Multipart 中发送的内容,不同之处在于针对 Retrofit 的“Content-Transfer-Encoding”标头
Content-Disposition: form-data; name="id"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit
Content-Disposition: form-data; name=“post[body]"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit
Content-Disposition: form-data; name=“post[attachment]"; filename="images.jpg"
Content-Type: image/jpg
Content-Transfer-Encoding: binary
有什么线索吗?提前致谢
- - - - - - - - - - - - - - - -解决方案 - - - - - - - - - ----------------
最后,我以这种方式解决了,实际上我的答案非常接近@lazypig,这是一个很好的指导方针
我唯一改变的是他的课程“ByteArrayTypedOutput”
我创建了一个名为“MultipartTypedOutputCustom”的类http://pastie.org/10549360
这就是我现在的界面
“PostsRetrofitAPI.java”类
@POST("/posts/add.json")
void addComment(@Body MultipartTypedOutputCustom parts,
Callback<Map<String, String>> callback);
“PostsService.java”类
//Properties
private PostsRetrofitAPI mApi;
...
@Override
public void addComment(ServiceResponseHandler<Map<String, String>> handler, String id, String body, TypedFile attachment) {
MultipartTypedOutputCustom parts = new MultipartTypedOutputCustom();
parts.addPart("id", new TypedString(id));
parts.addPart("post[body]", new TypedString(body));
parts.addPart("post[attachment]", attachment);
objectRetrofitCallback= new ObjectRetrofitCallback(handler, ServerError.class, ClientError.class);
mApi.addComment(parts, objectRetrofitCallback);
}