Search code examples
androidapiresthttprequestretrofit2

How to escape special characters in the API call?


I am trying to GET request for the API but a special character "*" (asterisk sign) breaks my API call and hence it is sent incomplete. Is there any way to escape it?

enter image description here

Instead of this:

https://rest2.bermanngps.cl/BermannRest/api/enviacomando?tk=3cf40d35c4e48b60e007cdc85f1342f5&comando=%24SRVFFFFFF%2C25%2C1*8F&md5pass=4e1ed8ef96fb83a0a30c39b0019fadc7&user=1017&avserie=12977

this is sent:

https://rest2.bermanngps.cl/BermannRest/api/enviacomando?tk=3cf40d35c4e48b60e007cdc85f1342f5&comando=%24SRVFFFFFF%2C25%2C1

I am using the GET request method of retrofit, using the repository to load Query strings dynamically. How would I use the URLEncoder method there?

    @GET("enviacomando")
    suspend fun getSendComando(
    @Query("tk") tk: String,
    @Query("comando") comando: String,
    @Query("md5pass") md5pass: String,
    @Query("user") user: String,
    @Query("avserie") avserie: String
    
    ): Response<SendComandoResponse>

Solution

  • You can use URLEncoder class for this. So you need to encode query part from URL with URLEncoder.

    String query = URLEncoder.encode("tk=3cf40d35c4e48b60e007cdc85f1342f5&comando=%24SRVFFFFFF%2C25%2C1*8F&md5pass=4e1ed8ef96fb83a0a30c39b0019fadc7&user=1017&avserie=12977", "utf-8");
    String url = "https://rest2.bermanngps.cl/BermannRest/api/enviacomando?" + query;