Handle different responses in Retrofit
public class Retro2Activity extends AppCompatActivity {
private String Root_url = "http://YOUR.API.com/api/", TAG = "Retro2Activity";
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callApi();
}
private void callApi() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Root_url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
DetailsAPI api = retrofit.create(DetailsAPI.class);
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("memberId", "tKBRLNiAfTpfYMmqlS6xHARRRR3RRRR3");
jsonObject.put("secanswer", "pyar1");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
Call<String> stringCall = api.securityCheck(body);
stringCall.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d(TAG, "onResponse: " + response.body().toString());
String mResponseObj = response.body().toString();
if (mResponseObj.contains("{")) {
JSONObject jsonObject1 = null;
JsonObject object = new JsonObject();
try {
jsonObject1 = new JSONObject(mResponseObj);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonObject1.has("memberId")) {
try {
String mMemberId = jsonObject1.getString("memberId");
Log.d(TAG, "memberId: " + mMemberId);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else { // this is string response.
Log.d(TAG, "String response :: " + mResponseObj);
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.d(TAG, "onFailure: " + call.toString());
}
});
}
}
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface DetailsAPI {
@POST("registersignin/resetpassword")
Call<String> securityCheck(@Body RequestBody body);
}
dependencies {
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.excelsoftservices.user2.retrofitmultiresponse">
<uses-permission android:name="android.permission.INTERNET"/>
..... ...... ......
</mainifest>
Logic is taken from : iagreen from https://stackoverflow.com/questions/32617770/how-to-get-response-as-string-using-retrofit-without-using-gson-or-any-other-lib