Search code examples
androidretrofitretrofit2

Sending plain text as POST body causes issue in retrofit


I'm making POST request to my backend, but i'm getting a 400 only using retrofit. I dug more into the issue and realized since my POST body is a plain string (not JSON), whenever I have double quote, it puts a back slash behind it and then sends the request. Here is the call:

@POST("/endpoint")
Observable<Result<MyResponse>> myApiCall(@Body String body);

I did some research and people suggested that I need to add a StringConverterFactory, but that didn't help (I followed this link: String converter factory )

I think that link in retrofit github page is outdated!


Solution

  • Try this ..

    @POST("/endpoint")
    Observable<Result<MyResponse>> myApiCall(@Body RequestBody body);
    
    RequestBody body= RequestBody.create(MyRequest.create("data"));
    
    public abstract class StringRequestBody extends RequestBody {
    
            public static RequestBody create(String content) {
                MediaType contentType = MediaType.parse("application/plain");
                Charset charset = Util.UTF_8;
                if (contentType != null) {
                    charset = contentType.charset();
                    if (charset == null) {
                        charset = Util.UTF_8;
                        contentType = MediaType.parse(contentType + "; charset=utf-8");
                    }
                }
                byte[] bytes = content.getBytes(charset);
                return create(contentType, bytes);
            }
    
        }