I have one API request where the POST
body is hex-encoded binary data transmitted as plain text. For reasons which I cannot discern, Retrofit2 is adding quotes around the hex-encoded string before adding it to the request, which causes the server to choke on it and complain about a malformed request.
We're in the middle of converting our app from original Retrofit to Retrofit2, and none of the payload generation code has changed at all.
I've been able to work around this problem by using an Interceptor
to remove the enclosing quotes from the request body at runtime, but that seems like a really daft hoop to have to jump through and I'd much rather not have the quotes appear in the first place.
My interface looks like this:
public interface SampleApi {
@POST("sample-endpoint")
Call<ApiResponse> postThing(@Body String hexEncodedData,
@Header(HttpHeaders.DATE) String gmtDateStr,
@Header("X-CUSTOM-ONE") long custom1,
@Header("X-CUSTOM-TWO") String custom2);
}
I've experimented with setting the Content-Type
header to various values with no apparent effect. I haven't built a custom type converter yet because having to make one of those for a plain old string seems like it shouldn't be necessary.
Can someone tell me what I'm doing wrong?
String text = "plain text request body"; RequestBody body = RequestBody. create(MediaType. parse("text/plain"), text); Call<ResponseBody> call = service. getStringRequestBody(body); Response<ResponseBody> response = call.
Double quotes is logical, as retrofit is sending data in json format so double quotes if type String . Try this it might help you .
public interface SampleApi {
@POST("sample-endpoint")
Call<ApiResponse> postThing(@Body RequestBody hexEncodedData,
@Header(HttpHeaders.DATE) String gmtDateStr,
@Header("X-CUSTOM-ONE") long custom1,
@Header("X-CUSTOM-TWO") String custom2);
}
String strRequestBody = "body";
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"),strRequestBody);
Update, for Kotlin the Code_Life code should look like this:
interface SampleApi {
@POST("sample-endpoint")
suspend fun postThing(
@Body presentation: RequestBody,
@Header(HttpHeaders.DATE) gmtDateStr: String,
@Header("X-CUSTOM-ONE") custom1: Long,
@Header("X-CUSTOM-TWO") custom2: String
): Call<ApiResponse>
}
val strRequestBody = "body"
val requestBody = strRequestBody.toRequestBody("text/plain".toMediaTypeOrNull()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With