问题
So I'm looking to make a request to our api to log in a user, however there is a section that gets encoded in the Retrofit 2 method even though its set as encoded = true
. The base url is https://testapi.test.ie
The parameter I pass as the serverext
is mdc.php?action=
However even after setting encoded = true
the resulting request body is: https://testapi.test.ie/mdc.php%3Faction=login_user&ts=1482924232742
where I require it to be: https://testapi.test.ie/mdc.php?action=login_user&ts=1482924232742
So I can see the issue is the ?
symbol. Below is my retrofit method, if anyone can help with this I would appreciate it in order to achieve the correct
@retrofit2.http.POST("/{serverext}login_user&ts={timestamp}")
@retrofit2.http.Multipart
Call<LoginResponseModel> loginUser(@retrofit2.http.Path(value = "serverext", encoded = true) String server,
@retrofit2.http.Part(Constants.USER) String username,
@retrofit2.http.Part(Constants.PASS) String password,
@retrofit2.http.Path("timestamp") Long timestamp);
回答1:
You use it incorrect. Path is path, Query is query. You need to rewrite your code to use this separately.
@retrofit2.http.POST("{serverext}")
@FormUrlEncoded
Call<LoginResponseModel> loginUser(@retrofit2.http.Path(value = "serverext", encoded = true) String server,
@retrofit2.http.Field(Constants.USER) String username,
@retrofit2.http.Field(Constants.PASS) String password,
@retrofit2.http.Query("timestamp") Long timestamp,
@retrofit2.http.Query("action") String action);
loginUser("mdc.php", username, pass, 42, "login_user")
回答2:
You need to use @FormUrlEncoded
. And you don't need to include package name in all declarations! just import them! its more neat and clean!
@POST("/{serverext}login_user&ts={timestamp}")
@Multipart
@FormUrlEncoded
Call<LoginResponseModel> loginUser(@Path(value = "server", encoded = true) String server,
@Part(SyncStateContract.Constants.USER) String username,
@Part(SyncStateContract.Constants.PASS) String password,
@Path("timestamp") Long timestamp);
来源:https://stackoverflow.com/questions/41361297/issue-with-special-characters-in-retrofit-2-encoding