Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Retrofit api call with space in parameter

I am trying to make an API call using Retrofit 1.x:

@POST("/test?api-version=1.0")
void createMyStuff(
        @Header("X-Signature") String authorization,
        @Query(value="nickname") String nickname,
        @Query("language") String language,
        Callback<MyAPIResponse> cb);

the issue is : nickname can have spaces in it. So, before make the call, if nickname is "John Doe" (two spaces), I replace space in it and send it like : "John%20%20Doe" in the API call.

It fails with 400, Bad request.

The URL reported in the errorResponse object is : https://.com/foo/test?nickname=john%2520%2520doe&language=en-US

Notice that the %20 is replaced by %2520

What I investigated : there isn't a definite answer. Someone on SO suggested in a thread to use FunName(value="apiname",encodeValue=true) But the encodeValue isn't resolving.

I also tried encoding with UTF-8 and it doesnt work. I am not sure about URL encoding since this is not really URL and will be only part of it.

Appreciate any help.

like image 632
techtinkerer Avatar asked Oct 23 '25 18:10

techtinkerer


2 Answers

In Retrofit2 Parameter names and values are URL encoded by default. You need to add encoded = true to change this behaviour.

void createMyStuff(
    @Header("X-Signature") String authorization,
    @Query(value="nickname", encoded = true) String nickname,
    @Query("language") String language,
    Callback<MyAPIResponse> cb);
like image 87
Kanchan Pal Avatar answered Oct 26 '25 08:10

Kanchan Pal


Actually %25 is encoding of % so when you put %20 it encodes % to %25 and 20 remains same. so you have to false its encoding in @Query parameter

@Query(value="nickname",encodeValue = false) String nickname

Now you can call it with %20 it will work fine

createMyStuff("Auth","John%20%20Doe","lang",new Callback<MyResponse>{....});
like image 38
Adnan Ali Avatar answered Oct 26 '25 06:10

Adnan Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!