Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple headers in retrofit responses in Android

In my application i want get some data from server and for this i used retrofit.
I should add some Headers but after run application show me ForceClose error!

ApiServices codes :

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>>
}

My Retrofit version is 2.5.0 !

In retrofit documents i read for set multiple header i should use {} into Headers such as @Headers({...}) , but after add {} show me error and i can't use {}!

Logcat error :

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)

How can i fix it?

like image 503
DJ Al Avatar asked Jan 26 '23 11:01

DJ Al


2 Answers

To change

"Content-Type : application/json"

to

"Content-Type: application/json"

Just remove the blank after Content-Type :)

like image 89
Library545 Avatar answered Feb 11 '23 23:02

Library545


You can use HeaderMap, same

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>>
like image 20
Cuong Nguyen Avatar answered Feb 11 '23 23:02

Cuong Nguyen