POST request with Android Annotation REST Service - android

I am using Android Annotation in my project and trying to send POST request through following code, however there is something wrong in following code as I am not getting response as expected:
#Rest(rootUrl = "http://xyz.com", converters = {GsonHttpMessageConverter.class})
public interface A {
#Post("/authenticate/email/")
public Object attemptLogin(Map data);
}
Where data is (key, value) pair. Is there anything I am missing perhaps Do I have to set request-header or data should not be JSON?

I found the solution from Rest client using Android-Annotations.
Like the GET requests, it is extremely simple to send POST requests using Android-Annotations. One difference is that you need to define the parameters that you are going to send as a custom class (e.g. Event class in the example below) or if you want to control this dynamically, then a Map (e.g. a MultiValueMap). The url for the request can still be constructed in a similar fashion using the variables enclosed inside {...} and the response can be handled similarly as in GET requests.
#Post("/events")
void addEvent(Event event);
#Post("/events/{id}")
void addEventById(Event event, long id);
#Post("/authenticate/event/")
Object authenticateEventData(MultiValueMap data);

Related

populate app with dummy endpoint retrofit values without having Json responses but only data Classes

I have an app with a lot of Retrofit endpoints. I need to run this app in the emulator without internet because I do not have access anymore to the server, I am happy with fake data, so for instance if is an Int I would be happy with a random number, if is a string with whatever string.
Also I want to be able to test this app, how can I create dummy json files on the basis of the data classes in moshi, interface endpoints?
In theory on the base of all the moshi data classes, I could write some fake data, but it will take me weeks
I know there are a number of nice tools as RESTMock, but they always follow an implementation as
RESTMockServer.whenGET(RequestMatchers.pathEndsWith("/data/example.json")).thenReturnFile(
"users/example.json");
but I want to know how to automate the process, without writing a json file myself
It should be your choice of the level on which to mock. You can mock jsons if you use rest mock server, but you can go at the higher level and mock entity that actually uses your retrofit interface, or actually mock rest interface itself:
public interface RESTApiService {
#POST("user/doSomething")
Single<MyJsonResponse> userDoSomething(
#Body JsonUserDoSomething request
);
}
public class RestApiServiceImpl {
private final RESTApiService restApiService;
#Inject
public RestApiServiceImpl(RESTApiService restApiService) {
this.restApiService = restApiService;
}
public Single<MyUserDoSomethingResult> userDoSomething(User user) {
return restApiService.userDoSomething(new JsonUserDoSomething(user))
.map(jsonResponse -> jsonResponse.toMyUserDoSomethingResult());
}
}
Clearly you can pass mock version of RESTApiService into RestApiServiceImpl and let it return hand-mocked responses. Or moving same direction you could mock RestApiServiceImpl itself and thus mock not at the json models level, but entities level.

How to handle such a json properly?

The problem is next.
In response I have JSON like
{
object: {
// a lot of different fields
}
}
I use Retrofit with gson parser. What I really need is just this object. I don't want to create class for response with the only one field. All responses server send in a such manner. As far I understand somewhere I need place simple code for fetching that one object and then use default parser for it.
Probably sorry for stupid question. I used Volley and there was quite a different approach.
Instead of creating a special class to handle this (and another special class for every other server response), just use Map<String, YourRealObjectType>. Then use this method to extract the YourRealObjectType instance for each response:
public static <T> T getFirstValue(Map<String, T> map) {
return map.values().iterator().next();
}
you can convert class into JsonObject class. then cal iterate all the elements in it one by one
#Get
ObservablegetData();
Note : use JsonObject not JSONObject

Retrofit / Robospice handle multiple response objects

How do I make Retrofit / Robospice handle my api responses in a way that I can get an empty JSON response body like: {}, but also a regular JSON response body?
Currently the empty response body initialises a new POJO, but I only want this to happen if there is actually a filled response body.
I have an object that contains three booleans, and these will always be set to false, while this shouldn't happen.
I somehow have the idea this is caused by my GSON deserializer (I use the default one), but don't know where to start for something like this.
Thanks for any help. :)
Why not using Boolean instead of boolean? That way the default value in null rather than false
Retrofit doesn't touch fields if there's no such fields in json. So init them by yourself.
public class Response {
public boolean value = true;
}

Retrofit: is it possible to pass a bean and get a form-encoding?

I'd like to send a POST request with a content like the following:
api=1&os=android&appVersion=12345
Is it possible to have a POJO with just that variables and pass that to
#FormUrlEncoded
#POST("/sendData")
void sendData(#FieldMap MyPojo myPojo, Callback<MyResponse> callback);
With FieldMap it doesn't work, is there another way?
Unfortunately this won't work out of the box. You have two options:
If you only have a handful of Pojos, you can define a MyPojo.toFieldMap() method to build a field map of form values and pass it to your sendData() method.
If you have a large number of Pojos, you can write a custom FormEncodedConverter by implementing the Converter interface in your project. I reckon this will need a combination of annotations and reflection to discover the public members of your MyPojo class. Examples of custom converters are available here.

Is there a hook in Retrofit to get the last request details?

I'm using ACRA to report exceptions and would like to include the last API call (and potentially the response body) as part of the custom data that can be supplied. I've been looking over the available RestAdapter.Builder interfaces but don't see one that supplies what I'm looking for. Effectively, I'd like access to what's put into Logcat when full logging is enabled.
Is there a way to get the last URL, headers, and response body within Retrofit so I can set custom ACRA fields?
Retrofit allows specifying a Profiler which gets invoked immediately before and after requests are made.
public interface Profiler<T> {
T beforeCall();
void afterCall(RequestInformation info, long elapsedTime, int statusCode, T beforeData);
}
While you don't get access to the actual body, you get a good bit of information about it.

Categories

Resources