Retrofit将multipart body转换回文件

时间:2017-02-23 06:54:20

标签: android multipartform-data retrofit2

我使用multipart将数据上传到服务器。问题是后端开发人员告诉我上载过程中上传的文件已损坏。

那么有没有办法在本地测试这些文件?我可以将文件转换为多部分,然后将其重新转换为文件以进行测试吗?

我正在使用Retrofit 2

由于

1 个答案:

答案 0 :(得分:0)

  

询问你的后端开发人员,如果它是图像,他是否希望文件为二进制文件或base64,然后相应地发送文件   您还可以记录帖子正文中发送的数据

这里是用于记录您通过改造发送的数据的代码

public class RetrofitClient {


private RetrofitClient() {
}




public static Retrofit getApiClient(String baseHost) {

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

//设置所需的日志级别         logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header(Util.HEADER_KEY, ""+Util.HEADER_VALUE); // <-- this is the important line

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    OkHttpClient client = httpClient.build();


    Retrofit retrofit = new Retrofit.Builder()

            .baseUrl(baseHost)

            .addConverterFactory(new NullOnEmptyConverterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();


    return retrofit;
}

}