How to get string response from Retrofit2?
Solution 1:
Add Retrofit2 and ScalarsConverterFactory to your Retrofit.Builder.
adapterBuilder = new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
To use ScalarsCoverter add following dependency to your build graddle
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0' //Adding Retrofit2
For API Call use:
Call <String> *****
Android Code :
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.i("Response", response.body().toString());
//Toast.makeText()
if (response.isSuccessful()){
if (response.body() != null){
Log.i("onSuccess", response.body().toString());
}else{
Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
}
}
Solution 2:
I take a look at Retrofit library and noticed that it parses response according to the type class inside Call<T>
. So you have two option:
1st: create a class according to the response from the server.
2nd: get the response and handle it yourself (Not recommended Retrofit already handles it. So why do you use Retrofit as it is tailored for this job). Anyway instead of Call<String>
use Call<ResponseBody>
and Call<ResponseBody> signin = service.jquery();
after this put the following
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
// handle success
String result = response.body().string();
}
@Override
public void onFailure(Throwable t) {
// handle failure
}
});