How to get the result of the Request in Retrofit 2.0

5

Well, I'm starting to study Android, I even made an application with Volley but a friend indicated Retrofit because it was much faster and "simple". But I still can not understand much.

I have a WebService where I want to log in. I have to send information that I get through facebook, like Email, Name, Access_token .. Then my Ruby application validates the login and returns an Api_key for future requests. Until then I was able to do the request, but I can not get the API_KEY that my WebService returns in JSON format.

My interface:

public interface APIService {

 @FormUrlEncoded
 @POST("login")
 Call<JSONObject> createUser(@Field("name") String name,
                             @Field("email") String email,
                             @Field("access_token") String access_token,
                             @Field("provider") String provider);

}

Generating Service Class:

public class ServiceGenerator {

public static final String API_BASE_URL = "https://rocky-cliffs-4726.herokuapp.com/api/v1/";

 private static OkHttpClient httpClient = new OkHttpClient();

 private static Retrofit.Builder builder =
         new Retrofit.Builder()
                 .baseUrl(API_BASE_URL)
                 .addConverterFactory(GsonConverterFactory.create());

 public static <S> S createService(Class<S> serviceClass) {
     Retrofit retrofit = builder.client(httpClient).build();
     return retrofit.create(serviceClass);
 }
}

In my activity I have the method:

public void logar(String name, String email, String acess_token, String provider) {

    APIService service = ServiceGenerator.createService(APIService.class);

    Call<JSONObject> call = service.createUser(name, email, acess_token, provider);
    call.enqueue(new Callback<JSONObject>() {
        @Override
        public void onResponse(Response<JSONObject> response, Retrofit retrofit) {
            try {
                String api_key = response.body().getString("api_key");
                Log.i("TAG",api_key);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Throwable t) {

        }
    });
}

The JSON that my application returns:

{"success" : true, "json" : {"data": {"api_key":"API_KEY_AQUI"}}}
    
asked by anonymous 09.12.2015 / 23:00

1 answer

1

return the following json

{"api_key":"API_KEY_AQUI"}

Create a model class that represents the same

public class suaclasse{
 private String api_key;
//get and set
}

Update your interface

@FormUrlEncoded
 @POST("login")
 Call<SuaClasse> createUser(@Field("name") String name,
                             @Field("email") String email,
                             @Field("access_token") String access_token,
                             @Field("provider") String provider);

Inside of onResponse do:

response.body().getApiKey();//metodo get definido em SuaClasse
    
22.03.2016 / 14:27