在 KtorClient 的 DefaultRequest 中声明 ContentType = Application.Json 后,我可以更改特定请求的 ContentType 标头吗

EGO*_*IND 7 android content-type ktor

我正在开发我的 android 项目,我正在创建一个请求函数来上传文件,该函数发出如下请求,

httpClient.put(uri) {
    body = MultiPartFormDataContent(formData {
        append("file", fileContent, Headers.build {
            append(HttpHeaders.ContentType, fileMimeType)
            append(HttpHeaders.ContentDisposition, ContentDisposition.File.withParameter(ContentDisposition.Parameters.FileName, fileOriginalName))
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这个请求有一个 ContentType 标头,但我已经在我的 Ktor HttpClient 中声明了 ContentType 标头,

install(DefaultRequest) {
                url {
                    protocol = URLProtocol.HTTP
                    host = baseURL
                }

                headers {
                    append(HttpHeaders.ContentType, ContentType.Application.Json)
                    append(HttpHeaders.Authorization, accessToken)
                    append(USER, user)
                }
            }
Run Code Online (Sandbox Code Playgroud)

所以我的问题是我的请求将采用哪种 ContentType?如果它不能接受我在请求函数中指定的 ContentType 那么我怎样才能让它接受与默认类型不同的 ContentType 呢?

Ale*_*man 0

如果您尝试Content-TypeDefaultRequest功能中设置标题,那么您将得到io.ktor.http.UnsafeHeaderException: Header(s) [Content-Type] are controlled by the engine and cannot be set explicitly.

\n

因此,如果删除该行append(HttpHeaders.ContentType,ContentType.Application.Json),则Content-Type请求的 将会是multipart/form-data变量的Content-Type正文file部分 \xe2\x80\x92 值fileMimeType

\n