【问题标题】:What is the best way to send @Multipart file/bitmap and extra parameters with retrofit 2?使用改造 2 发送@Multipart 文件/位图和额外参数的最佳方式是什么?
【发布时间】:2016-11-10 00:52:18
【问题描述】:

我有一个助手类:

public class RequestPart {
    public static RequestBody createFromBitmap(Bitmap bitmap) {
        return RequestBody.create(MediaType.parse("image/png"), Utils.getBytes(bitmap));
    }

    public static RequestBody createFromObject(Object value) {
        return RequestBody.create(
                MediaType.parse("multipart/form-data"), String.valueOf(value));
    }

    public static Map<String, RequestBody> convertMap(Map<String, Object> map) {
        Map<String, RequestBody> result = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof Bitmap) {
                result.put(entry.getKey(), createFromBitmap((Bitmap) entry.getValue()));
            } else {
                result.put(entry.getKey(), createFromObject(entry.getValue()));
            }
        }
        return result;
    }
}

我是这样用的:

Map<String, Object> params = new HashMap<>();
params.put("profile[param1]", String);
params.put("profile[param1]", Object);
params.put("profile[param1]", int);
params.put("profile[param2]", Bitmap);
params.put("profile[param2]", Bitmap);

retrofitService.updateProfile(RequestPart.convertMap(params));

改造:

@Multipart
@POST("api-patient/upload/something.json")
Call<User> uploadStateId(@PartMap Map<String, RequestBody> params);

我尝试仅包装位图参数,但是当我将字符串发送到服务器时,例如@PartMap Map&lt;String, String&gt; params,它会将值用双引号 ""Value"" 包装起来,这就是我对所有参数使用 RequestBody 的原因。

有人知道更好或更简单的方法吗?

【问题讨论】:

    标签: android retrofit multipart retrofit2


    【解决方案1】:

    嗨,请参考下面的博客链接在改造 2.0 中上传文件

    https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server

    它有很好的示例代码解释。

    【讨论】:

      猜你喜欢
      • 2021-03-04
      • 1970-01-01
      • 2011-06-18
      • 2010-09-10
      • 1970-01-01
      • 2014-01-15
      • 2022-12-05
      • 2017-01-03
      • 1970-01-01
      相关资源
      最近更新 更多