Android Retrofir2 Multipart 远程 API 调用将内容类型设置为“application/json”

问题描述 投票:0回答:1

我的 Android Retrofit2 应用程序中有以下远程 REST API 调用。

    @Multipart
    @POST("user/testupload")
    suspend fun uploadUImage(
        @Part  person: PersonFull,
        @Part image: MultipartBody.Part
    ) : BaseResponseModel

我创建了如下所示的两个部分,然后在我的代码中调用 api。

                val requestBody = file.asRequestBody("image/*".toMediaTypeOrNull())

                var filename = imageUrlPath + "_" + id.toString() + "_" + imageId

                val part2 = MultipartBody.Part.createFormData("person", Gson().toJson(personFull))
                val part1 = MultipartBody.Part.createFormData("productImage", filename, requestBody)

当代码到达终点时,我收到以下错误:

Content type 'application/octet-stream' not supported

如何将第 1 部分的内容类型更改为“application/json”?

android kotlin retrofit2 multipartform-data multipart
1个回答
0
投票

正如我在评论中提到的,您可以在方法上添加 Header,也可以将 httpClient 添加到改造中。 添加标题的语法。

 @Headers("Content-Type: application/json")
 @POST("user/testupload")
 suspend fun uploadUImage(
    @Part  person: PersonFull,
    @Part image: MultipartBody.Part
 ) : BaseResponseModel

如果您有许多 api 方法需要调用,那么在每个请求中添加标头会很麻烦,因此您需要将 http 客户端添加到改造实例中。 首先创建一个http客户端(从我的旧项目复制,因为它是java中的,所以下面的代码是java中的)

OkHttpClient httpClient = new OkHttpClient();
    httpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Request.Builder requestBuilder = chain.request().newBuilder();
            requestBuilder.header("Content-Type", "application/json");
            return chain.proceed(requestBuilder.build());
        }
    });

然后将this实例添加到retrofit中。

 Retrofit retrofit = new 
 Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
© www.soinside.com 2019 - 2024. All rights reserved.