将内容类型上传为 audio/mp3 后,Retrofit 会将内容类型覆盖为 multiformpartbody/form-data

Retrofit is overriding the Content Type to multiformpartbody/form-data after uploading it as audio/mp3

我正在使用 Retrofit 将文件上传到 AWS S3,但是每次上传时内容类型都会被覆盖。我有 CONTENT-TYPE audio/mp3 但是 S3 上的文件被覆盖为内容类型 multiformpartbody/form-data。我做错了什么?

        File file = new File(String.valueOf(Uri.parse(selectedImagesList.get(current_image_uploading))));
        ProgressRequestBody requestFile = new ProgressRequestBody(file, "audio/mp3");

        MultipartBody.Part body =
                MultipartBody.Part.createFormData("audio", file.getName(), requestFile);

        RetrofitInterfaces.IUploadMP3 service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.IUploadMP3.class);

        Call<Void> call = service.listRepos(uploadUrls.get(current_image_uploading), body);

您很可能需要在发送请求时覆盖 header。您可以为每个请求执行此操作:

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

        Request request = original.newBuilder()
            .header("Content-Type"," audio/mpeg") //Set the content type here
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

OkHttpClient client = httpClient.build();  
Retrofit retrofit = new Retrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

或者,如果您不想覆盖每个请求,您可以像这样为您的调用做一个静态覆盖:

public interface YourService {  
    @Headers("Content-Type: audio/mpeg")
    @GET("/your/path")
    Call<List<Task>> myFunction();
}

两个例子都可以找到here: