javaandroidserializationandroid-annotationsspring-android

Handling POST requests with Android Annotations


I am trying to consume a RESTful API using AA. My API receives email and password request parameters (not JSON!) and returns an APIKey (which I use Jackson2 to deserialize).

Ideally, I want to use a regular old Map<String, String> to send the email and password, but it appears AA requires me to use a MultiValueMap (which is a Map<K,List<V>>), or a custom class (Event, which has no source shown).

When using a MultiValueMap, an array is sent. I am not sending an array of email and passwords, I am sending a single email and password:

// LoginFragment.java            
MultiValueMap<String, String> credentials = new LinkedMultiValueMap<String, String>();
credentials.add("email", email);
credentials.add("password", password);
APIKey resp = userRest.login(credentials);


// UserRest.java
@Post("user/login")
public APIKey login(MultiValueMap credentials);

Which trips up my API, because it expects a String rather than an array of Strings.

So I'm thinking I have to create a custom Credentials object to hold my email and password, and somehow get it serialized to be sent to the server. Could someone help me out with this?


Solution

  • Have you not looked at using the built in Authentication mechanisms that Android Annotations provides? Like Basic Auth or OAuth? This might be a cleaner solution.

    https://github.com/excilys/androidannotations/wiki/Authenticated-Rest-Client

    I have used the Basic Auth options - https://github.com/excilys/androidannotations/wiki/Rest%20API

    You just need to add a method to your interface:

    void setHttpBasicAuth(String username, String password);
    

    Then call that before making the API call. There should be a similar option for OAuth.

    EDIT: You can create a Login POJO to POST to your API:

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @Generated("org.jsonschema2pojo")
    @JsonPropertyOrder({
            "name",
            "password"
    
    })
    public class Login{
        @JsonProperty("name")
        private String name;
        @JsonProperty("password")
        private String password;
    
    }
    

    and then in your API Interface you can do the following:

      @Post("user/login")
        public APIKey login(Login credentials);
    

    This will then POST your data to the /user/login method. You might need to add an interceptor depending on what kind of data you wish to parse ie converters = { MappingJacksonHttpMessageConverter.class } etc.