Pass parameters in the Retrofit2 GET method for Android

Asked

Viewed 357 times

2

Talk to me, baby?

I’m trying to pass a parameter in the retrofit, but I’m not getting it. I confess that I’m very beginner in Android. I did a little research, but what I tried didn’t work out so far.

How I tested my api method in Postman: http://localhost:8080/api/user/? [email protected]

So far, so quiet.

Userservice interface

public interface UserService {

    @GET("user/?userEmail")
    Call<User> getUserByEmail(@Query(value = "email", encoded = true) String email);

Call on the Main Activity

public void getUserByEmail(String email) {

       Call<User> call = userService.getUserByEmail(email);

       call.enqueue(new Callback<User>() {
           @Override
           public void onResponse(Call<User> call, Response<User> response) {
               if (response.isSuccessful()) {
                   User userResponse = response.body();
                   Long id = userResponse.getUserId();
                   String emailU = userResponse.getEmail();
               }
           }

           @Override
           public void onFailure(Call<User> call, Throwable t) {

           }
       });


   }

And well, that’s it. Initially I was using @Path on the interface and passing the same string as the url that was in Postman.

  • The service is waiting userEmail or email?

  • Dude, I just saw your answers here. In my api, the parameter is userEmail. I think I got it. I’ll try it here and then I’ll give you a feedback

1 answer

3


You must specify the name of the parameter only in the annotation @Query, in your case the URL mount will be incorrect: user/?userEmail&email=xpto

Changing the path as follows shall have effect

@GET("/user")
Call<User> getUserByEmail(@Query(value = "email", encoded = true) String email);

Check if your annotation should be @Query(value = "email", encoded = true) or @Query(value = "userEmail", encoded = true).

You can also use @Path if you prefer:

@GET("/user?userEmail={userEmail}")
Call<User> getUserByEmail(@Path("userEmail") String email);

If you have many parameters, you can use @QueryMap, that makes it easier to pass several parameters without needing a template:

@GET("/user")
Call<User> getUserByEmail(@QueryMap Map<String, String> params);
  • Man, it worked out here. Thanks for the help, I’ll mark it as the best answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.