如何在 Android 中的改造响应中添加多个标头

DJ *_* Al 11 android kotlin retrofit retrofit2

在我的应用程序中,我想从服务器获取一些数据,为此我使用了改造
我应该添加一些标题,但运行应用程序后显示ForceClose错误!

Api服务代码:

interface ApiServices {
    @Headers(
        "Accept: application/json",
        "Content-Type : application/json"
    )
    @POST("user/get-password")
    fun sendPhoneNumber(@Body body: LoginSendPhoneBody): Single<Response<LoginSendPhoneResponse>>

    @Headers(
        "Accept: application/json",
        "Content-Type : application/json"
    )
    @POST("addresses")
    fun newAddress(@Header("Authorization") userToken: String, @Body body: NewAddressBody):
            Single<Response<NewAddressResponse>>
}
Run Code Online (Sandbox Code Playgroud)

我的Retrofit版本是2.5.0

改造文档中,我阅读了设置多个标头的内容,我应该将其用于{}头,例如@Headers({...}),但添加后{}显示错误,我无法使用{}

日志猫错误:

java.lang.IllegalArgumentException: Unexpected char 0x20 at 12 in header name: Content-Type 
    at okhttp3.Headers.checkName(Headers.java:261)
    at okhttp3.Headers$Builder.add(Headers.java:311)
    at retrofit2.RequestFactory$Builder.parseHeaders(RequestFactory.java:283)
    at retrofit2.RequestFactory$Builder.parseMethodAnnotation(RequestFactory.java:224)
    at retrofit2.RequestFactory$Builder.build(RequestFactory.java:161)
    at retrofit2.RequestFactory.parseAnnotations(RequestFactory.java:65)
    at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:25)
    at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:168)
    at retrofit2.Retrofit$1.invoke(Retrofit.java:147)
    at java.lang.reflect.Proxy.invoke(Proxy.java:913)
    at $Proxy2.sendPhoneNumber(Unknown Source)
    at com.app.app.data.network.ApiUseCase.getSendPhoneNumber(ApiUseCase.kt:42)
Run Code Online (Sandbox Code Playgroud)

我该如何修复它?

小智 12

改变

"Content-Type : application/json"
Run Code Online (Sandbox Code Playgroud)

"Content-Type: application/json"
Run Code Online (Sandbox Code Playgroud)

只需删除后面的空白即可Content-Type:)


小智 9

您可以使用 HeaderMap,同样

val header = HashMap<String, String>()
    header["Accept"] = "application/json"
    header["Content-Type"] = "application/json"
    header["Authorization"] = "userToken"



@POST("addresses")
    fun newAddress(@HeaderMap headers: Map<String, String>, @Body body: NewAddressBody): Single<Response<NewAddressResponse>>
Run Code Online (Sandbox Code Playgroud)


Muh*_*far 5

在 Kotlin API 接口中:

 @Headers(
        "Accept: application/json",
        "User-Agent : PostmanRuntime/7.29.0",
        "Accept : */*",
        "Accept-Encoding : gzip, deflate, br",
        "Connection : keep-alive"
    )
Run Code Online (Sandbox Code Playgroud)