Retrofit Dynamic ResponseBody - java

I am planning to make one common service class with the use of Retrofit,
#GET
Call<ResponseBody> makeGetRequest(#Url String url);
#POST
Call<ResponseBody> makePostRequest(#Url String url, #Body RequestBody parameters);
In this code i need to pass (ResponseBody) as a dynamic JSON POJO class name , Like LoginRes
Say for Example ,
Call<LoginRes> // But this class will be dynamic
I will pass ResponseBody but that ResponseBody does not know which class i wanted to prefer.
why i want this because , after result
gson.fromJson(response, LoginRes.class);
so, after getting result from Retrofit we again need to convert to gson.fromJson.
so i wanted to pass dynamic Response as Retrofit so that it will response according to my pojo class,
I know this is working fine when i pass LoginRes instead of ResponseBody because as i already told to Response that we need that response in LoginRes.
So if i pass
Call<LoginRes> // if i pass this way its working fine no need to convert my response i can access my all properties from that LoginRes class directly.
This is my example to call a Web service.
Call<ResponseBody> call = apiService.makePostRequest("/Buyer/LoginApp", requestBody);
This is how i call the Service.
Let me know if i am unclear with explanation of my problem.
waiting for some good response and suggestions on this.
Thanks
Madhav

This is a bit tricky but you'll need to use a custom Retrofit Converter Factory with a custom GsonBuilder which uses a custom JsonDeserializer.
Furthermore you should define an interface (CustomResonse in my Example) for which the CustomJsonDeserializer is used. This is not needed, but otherwise the Deserializer gets used for every request.
public class CustomConverterFactory {
public static GsonConverterFactory create() {
return GsonConverterFactory.create(createGsonCustomDeserializer());
}
public static Gson createGsonCustomJsonDeserializer() {
return new GsonBuilder()
.registerTypeAdapter(CustomResponse.class, new CustomJsonDeserializer())
.serializeNulls()
.create();
}
}
And for the Deserializer:
public class CustomJsonDeserializer implements JsonDeserializer<CustomResponse> {
#Override
public CustomResponse deserialize(final JsonElement json, final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonObject()) {
JsonObject jsonObject = json.getAsJsonObject();
// Here you have to distinguish your class somehow
// Maybe read some Json field from your response
if (jsonObject.has("name")) {
JsonElement classes = jsonObject.get("name");
...
return context.deserialize(json, MyName.class);
}
...
// Default fallback: Deserialize as a fallback object
return context.deserialize(json, MyFallback.class);
} else {
throw new IllegalStateException();
}
}

Handle GET,POST or OTHER method Like this,
if (methodType.equalsIgnoreCase(CommonConfig.WsMethodType.GET)) {
apicall = getClient(CommonConfig.WsPrefix).create(ApiInterface.class).makeGetRequest(url + CommonConfig.getQueryString(new Gson().toJson(requestBody)), getAllHeader);
} else if (methodType.equalsIgnoreCase(CommonConfig.WsMethodType.POST)) {
apicall = getClient(CommonConfig.WsPrefix).create(ApiInterface.class).makePostRequest(url, RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(requestBody)), getAllHeader);
}
Handle Response Like this.
apicall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
}
Retrofit Code
private Retrofit getClient(String WsPrefix) {
//TODO 60 to 30 second at everywhere
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(WsPrefix)
.client(okHttpClient)
.build();
return retrofit;
}
Common Interface
interface ApiInterface {
#GET
Call<ResponseBody> makeGetRequest(#Url String url, #HeaderMap() Map<String, String> header);
#POST
Call<ResponseBody> makePostRequest(#Url String url, #Body RequestBody requestBody, #HeaderMap() Map<String, String> header);
}
ApiCallback
public interface ApiCallback {
void success(String responseData);
void failure(String responseData);
}

Related

WebClient giving MediaType not supported Exception when using class with custom getter setter as RequestBody

I have class all classes in my spring Webflux Application which has getter/setters without get and set prefix and setter return this. Hence i have also defined my custom Jackson Configuration for that which works fine with all my controllers successfully for serialising deserialising.
My Jackson Config
#Configuration
public class JacksonObjectMapperConfiguration implements Jackson2ObjectMapperBuilderCustomizer {
#Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder
.serializationInclusion(NON_NULL)
.failOnUnknownProperties(false)
.visibility(FIELD, ANY)
.modulesToInstall(new ParameterNamesModule(PROPERTIES));
}
}
My Request Class
#Accessors(chain = true, fluent = true)
#Getter
#Setter // from project Lombok
public class Test {
private String a;
private List<String> b;
}
Now if I make request using webclient like below
public Mono<Void> postRequest(String a, List<String> b) {
Webclient webclient = Webclient.create();
return webClient.post()
.uri("some_url")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new Test().a(a).b(b))
.retrieve()
.bodyToMono(Void.class);
}
I get an exception like below
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/json' not supported for bodyType=<Classpath>
but instead if i pass a Map like below, it works.
public Mono<Void> postRequest(String a, List<String> b) {
Webclient webclient = Webclient.create();
return webClient.post()
.uri(format("some_url")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new HashMap<String,Object>(){{put("a",a);put("b",b);}})
.retrieve()
.bodyToMono(Void.class);
}
I have tried removing #Accessor annotation and creating the getter setter myself but still it doesn't works.
I think the exception is occurring due to some deserialisation issue. I am not sure though. Jackson works fine with all my controllers in the application.
How can i make the first case work where i can provide a class as body instead of a Map?
Creating Webclient like below solved my issue.
public WebClient webClient() {
WebClient.Builder builder = WebClient.builder();
builder.exchangeStrategies(EXCHANGE_STRATEGIES)
.defaultHeader("content-type", "application/json");
return builder.build();
}
public static final ObjectMapper GSON_LIKE_OM = new ObjectMapper()
.setSerializationInclusion(NON_NULL)
.setVisibility(FIELD, ANY)
.configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(new ParameterNamesModule(PROPERTIES));
public static final ExchangeStrategies EXCHANGE_STRATEGIES = ExchangeStrategies
.builder()
.codecs(clientDefaultCodecsConfigurer -> {
clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(GSON_LIKE_OM, APPLICATION_JSON));
clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(GSON_LIKE_OM, APPLICATION_JSON));
}).build();

How to register custom TypeAdapter or JsonDeserializer with Gson in Retrofit?

I am using Retrofit in my project and I need some custom deserialization with some of the responses that the API I use returns.
Just for an example: I receive JSON like:
{ "status": "7 rows processed" }
( will be "0 rows processed" if request failed )
and I need to deserialize to an object like:
#Getter
#RequiredArgsConstructor
public static class Result {
private final boolean success;
}
I have created custom deserializer:
public class ResultDeserializer implements JsonDeserializer<Result> {
#Override
public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new Result( ! json.getAsJsonObject().get("status").getAsString().startsWith("0"));
}
}
and I am able to test it works when I register it like:
Gson gson = new GsonBuilder().registerTypeAdapter(Result.class, new ResultDeserializer()).create();
NOTE: this question is meant to be canonical/Q&A one and a inspired by the diffulty for me to find this when I need this information once in a year. So if the example seems to be artificial and stupid it is just because it should be simple. Hope this helps others also
The solution is to register customized Gson when building the Retrofit client. So after customizing Gson with custom JsonDeserializer like in question:
Gson customGson = new GsonBuilder()
.registerTypeAdapter(Result.class, new ResultDeserializer())
.create();
it is needed to register this Gson instance with Retrofit in building phase with help of GsonConverterFactory:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:8080/rest/")
.addConverterFactory(GsonConverterFactory.create(customGson))
.build();

Retrofit request body: Required fields

The process of using a request body is described in the official API Declaration page as such:
#POST("users/new")
Call<User> createUser(#Body User user);
While there is no guide for creating the User object, I imagine it can look something like this:
public class User {
public String name;
public String group;
}
By extension, this would result in a request body like this:
{
"name": string,
"group": string
}
By default, these fields seem to be optional. What is the best way I can make them required?
There are many ways of accomplishing such a behavior. You can:
... validate your objects to be POSTed before you invoke a Retrofitted-service (user input forms, etc), and let it fail fast.
... validate your domain objects, centralized, in a Retrofit request converter and use chained converters
... validate your data transfer objects objects (if you have any), centralized, after they are converted from domain objects and prepared to be sent
... rely on the server API implementation and don't care for validation at the client side: no need to duplicate server logic ad-hoc, you may run out sync with the server API validation, you write more code, etc. This is what I was suggesting you in that comment.
If you really need to validate the request bodies before they are sent, you should go with the first option. If you want to make the validation fully centralized, you can implement a custom Retrofit converter to make pre-validation on fly. (The code below uses Java 8 and a little bit of Google Guava, Retrofit 2 and Gson, however it can be easily reworked for another components).
Consider these:
interface IService {
#POST("/")
Call<String> post(
#Body User user
);
}
final class User {
final String name;
final String group;
User(final String name, final String group) {
this.name = name;
this.group = group;
}
}
Now we can implement Retrofit-stuff. The following mockOkHttpClient is a mock OkHttpClient to consume any request and respond with HTTP 200 OK and "OK".
private static final OkHttpClient mockOkHttpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> new Response.Builder()
.request(chain.request())
.protocol(HTTP_1_0)
.code(HTTP_OK)
.body(ResponseBody.create(MediaType.parse("application/json"), "\"OK\""))
.build()
)
.build();
Now let's make a simple test:
final Iterable<Retrofit> retrofits = ImmutableList.of(
getAsIsRetrofit(),
getValidatedDomainObjectsRetrofit(),
getValidatedDataTransferObjectsRetrofit()
);
final User user = new User("user", "group");
for ( final Retrofit retrofit : retrofits ) {
final IService service = retrofit.create(IService.class);
final String message = service.post(user).execute().body();
System.out.println(message);
}
As you can see, there are three Retrofit instances that are instantiated with different configurations to demonstrate each of them.
The following Retrofit instance does not care the validation itself. And this is another time I recommend you to go with: simply post what you get as is and let the server API implementation deal with it itself. Consider the API implementation to return nice responses like HTTP 400 Bad Request, etc.
private static Retrofit getAsIsRetrofit() {
return new Retrofit.Builder()
.client(mockOkHttpClient)
.baseUrl("http://whatever")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
The following Retrofit instance validates the given User object before it's converted to a Gson-friendly representation (depends on if you have domain objects to data transfer object transformations in your application):
private static Retrofit getValidatedDomainObjectsRetrofit() {
return new Retrofit.Builder()
.client(mockOkHttpClient)
.baseUrl("http://whatever")
.addConverterFactory(new Converter.Factory() {
#Override
public Converter<?, RequestBody> requestBodyConverter(final Type type, final Annotation[] parameterAnnotations,
final Annotation[] methodAnnotations, final Retrofit retrofit) {
if ( type != User.class ) {
return null;
}
final Converter<Object, RequestBody> nextConverter = retrofit.nextRequestBodyConverter(this, type, parameterAnnotations, methodAnnotations);
return (Converter<Object, RequestBody>) value -> {
if ( value instanceof User ) {
final User user = (User) value;
requireNonNull(user.name, "name must not be null");
requireNonNull(user.group, "group must not be null");
}
return nextConverter.convert(value);
};
}
})
.addConverterFactory(GsonConverterFactory.create())
.build();
}
And the next one validates data transfer objects before they are written to output streams. Probably the most low-level instance here.
private static Retrofit getValidatedDataTransferObjectsRetrofit() {
final Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new TypeAdapterFactory() {
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
if ( typeToken.getRawType() != User.class ) {
return null;
}
final TypeAdapter<T> delegateTypeAdapter = gson.getDelegateAdapter(this, typeToken);
return new TypeAdapter<T>() {
#Override
public void write(final JsonWriter out, final T value)
throws IOException {
if ( value instanceof User ) {
final User user = (User) value;
requireNonNull(user.name, "name must not be null");
requireNonNull(user.group, "group must not be null");
}
delegateTypeAdapter.write(out, value);
}
#Override
public T read(final JsonReader in)
throws IOException {
return delegateTypeAdapter.read(in);
}
};
}
})
.create();
return new Retrofit.Builder()
.client(mockOkHttpClient)
.baseUrl("http://whatever")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
Note that requireNonNull is a JDK 8 method, and if you want something like #NotNull, you can implement your own annotation processor, or find such an implementation in the Internet considering my implementation idea useless. :) However, I think you'd like the as-is approach the most.

Making a minimal post request with retrofit

I am trying to learn about Retrofit since it seems to take care of a lot of the issues I am currently having with JSON requests and handling.
first and foremost, I understand that the methods we use are defined inside of interfaces, while making simple requests to obtain data it is quite simple to specify what is to be retrieved from the url as well as all the necessary endpoints based on the famous github example.
So if we are retrieving information form the github api, we would first create all the necessary pojo models and such and then define the interface as:
public interface GithubService {
#GET("users/{username}")
Observable<Github>getGithHubUser(#Path("username")String userName);
}
From that on the main activity we would have something like:
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://api.github.com/")
.build();
GithubService githubService = retrofit.create(GithubService.class);
Observable<Github> githubUser = githubService.getGithHubUser("usersName");
githubUser.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.map(user -> "Github Username: " + user.getName() + "\nUrl:" +user.getUrl() + "\nfollowing: "+ user.getHireable())
.subscribe(userInfo -> Log.d("Output", userInfo));
My question here would be how to send JSON information if the url requires something like this:
"data={\"process\":\"procesNumber\", \"phone\":\"123456\"}"
Basically, in order to get any response form the server I have been doing this using simple okhttp:
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(CREATE_MEDIA_TYPE, "data={\"process\":\"procesNumber\", \"phone\":\"123456\"}");
String ALLWAYS_API = "http://something something bla bla";
Request request = new Request.Builder()
.url("https://blablabla")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
... etc etc etc
}
To my understanding, even I need to create a pojo class that represents the data that needs to be sent to retrofit, something along the lines of:
public class DataRequest {
final String proces;
final String phone;
DataRequest(String process, String phone) {
this.process = process;
this.phone = phone;
}
}
Which would comply to the information being sent to the request, but how would I actually parse that to the interface implementation?
interface DataService {
#Post(not a clue what to place here)
DataRequest postJson(#Body how?)
}
And how would I actually add that to the retrofit builder? The examples that I am using come from different forums on the web as well as other questions asked by other users, this one in particular helped a lot in understanding a couple of things: How to POST raw whole JSON in the body of a Retrofit request? but I still don't understand where everything goes and some of the other questions and examples are far too complex for what I need to do.
Ok, so in order to leave an answer here for anyone trying to do this. By default, retrofit comes with many utilities which handle the passing of data as JSON, but in this case what I am passing is a string that looks like json inside of a tag called data......I know..
But in order to answer this for the people facing similar issues, in order to pass in the string we need to import a scalar convertor much in the same way that we need to import a gson converter to work with our retrofit services:
compile 'com.squareup.retrofit2:converter-scalars:2.0.2'
After that, our service can be handled as:
public interface CreateService {
#Headers({ "Content-Type: application/x-www-form-urlencoded;charset=UTF-8"})
#POST("your/post/path/goes/here")
Call<String> getStringScalar(#Body String body);
}
I write my service generators in a separate file, in this case, the whole thing can be used in this way:
public class ServiceGeneratorWithScalarConvertor {
private static final String API_BASE_URL = "your/base/url/goes/here";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// basically, this code is the same as the one from before with the added instance of creating and making use of the scalar converter factory.....scratch that i took it off
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
builder.client(httpClient.build());
Retrofit retrofit = builder.build();
return retrofit.create(serviceClass);
}
}
From there, we can access the results with this particular method(i am using this method inside my main activity:
public void retroFitCreateAPIExample() {
CreateService service = ServiceGeneratorWithScalarConvertor.createService(CreateService.class);
String body = "data={\"process\":\"process1\",\"phone\":\"12345\"}";
Call<String> call = service.getStringScalar(body);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Log.d("Response Body>>>>>", response.body());
createR = new Gson().fromJson(response.body().toString(), CreateModels.class);
Log.d("CREATED RESPONSE",createR.getCreate().getStops().get(0).getCity());
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
The instance is this passed to the service generator that uses scalar convertors, the body of the post request is saved as a simple string(as it was specified in the interface) and we can do with the response whatever we want.

Unable to create converter for class com.squareup.okhttp.ResponseBody

Retrofit Documentation says:
"By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody...Converters can be added to support other types"
This implies I should be able to make a api call WIHTOUT using the GSON converter, and get my response in the form of a "ResponseBody" object.
but I still get error
java.lang.IllegalArgumentException: Unable to create converter for class com.squareup.okhttp.ResponseBody
here is my code
#GET("v1/search")
Call<ResponseBody> getArtists(#Query("q") String name, #Query("type") String searchType);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.spotify.com/")
.build();
api = retrofit.create(SpotifyApi.class);
api.getArtists(searchBox.getText().toString(), "artist")
.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Basically for I want to be able to use Retrofit in its purest/simplest form and just get a basic/raw response back. this is not for a real app, it's for experimentation.
You need to use okhttp3.ResponseBody from OkHttp 3.x (which Retrofit depends on). That error message indicates you are using the type from OkHttp 2.x.

Categories