I'm using retrofit2
com.squareup.retrofit2:retrofit:2.0.1
My rest API(Post) returns plain string as response
how to post String in body?
My code is
I'm using custom String Converter Factory
public final class ToStringConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
//noinspection EqualsBetweenInconvertibleTypes
if (String.class.equals(type)) {
return new Converter<ResponseBody, Object>() {
@Override
public Object convert(ResponseBody responseBody) throws IOException {
return responseBody.string();
}
};
}
return null;
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<String, RequestBody>() {
@Override
public RequestBody convert(String value) throws IOException {
return RequestBody.create(MediaType.parse("text/plain"), value);
}
};
}
return null;
}
}
and my Retrofit builder is
Retrofit retrofit = new Retrofit.Builder().baseUrl(root_url).addConverterFactory(new ToStringConverterFactory()).build();
and my callback is
Callback<String> callback = new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
System.out.println("===>>> onResponse body res "+response.body());
System.out. println("===>>> onResponse error body res "+response.errorBody());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
System.out.println("===>>> onFailure "+call.toString()+" "+t.toString());
t.printStackTrace();
}
};
My RetroService interface is
public interface RetroService {
@POST("/validateUser")
Call<String> login(@Body String body);
}
and the API call
Call<String> loginCall = service.login(req);
loginCall.enqueue(callback);
What i'm getting is in onresponse() response.body its always showing as null.
Please clarify what i'm doing wrong.
Thx in adv.