如何使用改装库同时发送@FormUrlEncoded和@Multipart请求



我正在编写一个客户端服务器Android应用程序。我需要通过POST请求将用户创建的文件(照片)发送到服务器。问题是,当我尝试发送文件时,我无法在请求中添加POST字段。也许我根本错了,这次手术应该换一种方式吗?

@FormUrlEncoded
@Multipart
@POST("/answer/add-file")
Call<AbstractServerResponse> sendSingleFile(@Query("access-token") String accessToken,
                                            @Query("w") String screenWidth,
                                            @Field("answer_id") Integer answerId,
                                            @Part("file") File fileToUpload);

当我尝试只以多部分的方式发送文件时,我会得到一个异常:

java.lang.IllegalStateException: JSON must start with an array or an object.

据我所知,之所以会发生这种情况,是因为请求的主体(主要部分)是空的。

当方法上存在@Multipart时,会使用Multipart请求。部件是使用@Part注释声明的。------来自http://square.github.io/retrofit/

我在我的项目中使用@Multipart,如下所示:

@POST("/{action}")//POST 多个文件
@Multipart
public void PostAPI(
    @Path(value = "action", encode = false) String action, 
    @Part("path") TypedFile[] typedFiles, 
    @PartMap Map<String, String> params, 
    Callback<APIResponse> callback);

也许你可以试试这个:

@Multipart
@POST("/answer/add-file")
Call<AbstractServerResponse> sendSingleFile(
    @Query("access-token") String accessToken,
    @Query("w") String screenWidth,
    @Part("answer_id") Integer answerId, 
    @Part("file") File fileToUpload);

不能在单个方法上同时使用@FormUrlEncoded@MultipartHTTP请求只能有一个Content-Type,并且这两个都是内容类型。

最新更新