I\'m trying to pass a string of the format below as the body of a http post request.
param1=PARAM1¶m2=PARAM2¶m3=PARAM3
But
Using Kotlin
For Retrofit 2 you can initialize retrofit with a Gson converter factory.
val builder = GsonBuilder().disableHtmlEscaping().create()
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(builder))
.client(monoOkHttpClient())
.build()
This builder should remove escaping from your json output.
Gradle file dependencies:
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
This issue can be fixed with below workaround.
@POST("yourString")
Call<YourResponseModel> yourCallMethod(@Query("yourKey") String yourValue,
@Query("yourKey") String yourValue,
@Query("yourKey") String yourValue);
Note : Don't use "@FormUrlEncoded" for this case.
Reference Here - https://github.com/square/retrofit/issues/1407
If you have a serialized class (like a HashMap) in the request body and you want to prevent encoding that (like in vezikon's and my problem), you can create a custom Gson with disabled escaping using:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Pass this converter to your rest adapter:
yourRestAdapter = new RestAdapter.Builder()
.setEndpoint(.....)
.setClient(.....)
.setConverter(new GsonConverter(gson))
.build();
This way the "=" characters in the post body stay intact while submitting.
To answer the question directly, you can use TypedString
as the method parameter type. The reason the value is being changed is because Retrofit is handing the String
to Gson in order to encode as JSON. Using TypedString
or any TypedOutput
subclass will prevent this behavior, basically telling Retrofit you will handle creating the direct request body yourself.
However, that format of payload is called form URL encoding. Retrofit has native support for it. Your method declaration should actually look like this:
@FormUrlEncoded
@POST("/oauth/token")
void getAccessToken(
@Field("param1") String param1,
@Field("param2") String param2,
@Field("param3") String param3,
Callback<Response> callback);