Android Retrofit 实现文字(参数)和图片一起上传?

Retrofit图文上传时,如何做到适应所有情况?
1.只有文字
2.只有图片
3.图文都有
使用post请求

阅读 5.7k
2 个回答
@Multipart
@POST("/xxx")
Observable<Result<String>> addInfo(@Part List<MultipartBody.Part> requestBodyMap);
        List<MultipartBody.Part> parts = new ArrayList<>();
        parts.add(toRequestBodyOfText("name", userName));
        parts.add(toRequestBodyOfImage("image",foundImage));
        ...
private MultipartBody.Part toRequestBodyOfText (String keyStr, String value) {
        MultipartBody.Part body = MultipartBody.Part.createFormData(keyStr, value);
        return body;
    }

    private MultipartBody.Part toRequestBodyOfImage(String keyStr, File pFile){
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), pFile);
        MultipartBody.Part filedata = MultipartBody.Part.createFormData(keyStr, pFile.getName(), requestBody);
        return filedata;
    }
推荐问题
宣传栏