In This blog, we will learn about how to Get Response as String from your Retrofit Call.
Many times, during app development we need to use third-party modules and their response is not in our hand. I faced the same issue the response sent from third-party module was a simple string (no formatting done for any parser to work).
Being familiar with retrofit and its custom Converters for the response I got stuck with the response from this API. The response was in front of me through logs but was not accessible as retrofit was rejecting to detect it. So, I had to change the request a bit but implementing it was very easy.
APPROACH
- Your Call Should Expect the Default ResponseBody Object in response.
- When the response is received you need to call response.body().string() method to get the response as a plain string.
CODE
Retrofit call Object :
1 2 3 4 5 6 |
@FormUrlEncoded @POST Call<ResponseBody> getStringResponse( @Url String url // add Fields required as per your use ); |
Retrofit Callback Object :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private Callback<ResponseBody> ResponseCallBack = new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { String responseRecieved = response.body().string(); // Add Your Logic }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }; |
And That’s It.
Keep coding and Keep Sharing 🙂