如何使用RxJava2和Retrofit2执行POST请求?

时间:2017-06-19 14:46:05

标签: android post retrofit2 rx-java2

我正在尝试一起学习RxJava2和Retrofit,现在,我知道如何调用GET请求。但我不知道如何做,POST,PUT ......等等。

我的AccountUserApi文件是:

@GET(LiveDataApi.GET_USER)
    Flowable<HttpCustomRes<UserPostData>> getUserData(@Path("id") long userId);

...

@POST(LiveDataApi.POST_LOGIN)
    Flowable<HttpCustomRes<User>> loginUser(@Body @Field("user") String username, @Body @Field("password") String password);

对于经理我:

    public class AccountUserManager {

        @Inject
        public AccountUserManager(){}

        public AccountUserApi getApi() {
            return HttpRetrofit.getInstance().getService(AccountUserApi.class);
        }

// THIS IS BAD :(
        public Flowable<User> loginUser(String username, String password){
            return getApi().loginUser(username, password).map(new Function<HttpCustomRes<User>, User>() {
                @Override
                public User apply(@NonNull HttpCustomRes<User> userPostDataHttpCustomRes) throws Exception {
                    if(userPostDataHttpCustomRes != null) {
                        return userPostDataHttpCustomRes.getData();
                    }else
                        return null;
                }
            });
        }

        public Flowable<UserPostData> getUserData(long userId){
            return getApi().getUserData(userId).map(new Function<HttpCustomRes<UserPostData>, UserPostData>() {
                @Override
                public UserPostData apply(@NonNull HttpCustomRes<UserPostData> userPostDataHttpCustomRes) throws Exception {
                    if(userPostDataHttpCustomRes != null) {
                        return userPostDataHttpCustomRes.getData();
                    }else
                        return null;
                }
            });
        }

        public Flowable<EmptyModel> setUserData(long userId, UserPostData userPostData){
            return getApi().setUserData(userId, userPostData).map(new Function<HttpCustomRes<EmptyModel>, EmptyModel>() {
                @Override
                public EmptyModel apply(@NonNull HttpCustomRes<EmptyModel> emptyModelHttpCustomRes) throws Exception {
                    if(emptyModelHttpCustomRes != null) {
                        return emptyModelHttpCustomRes.getData();
                    }else
                        return null;
                }
            });
        }

    }

如何使用RxJava2和Retrofit2执行POST请求?谢谢。

1 个答案:

答案 0 :(得分:1)

首先,我建议您使用retrolambda plugin以减少RxJava方法的详细程度。

对于请求,要发出POST请求,您必须发送一个表示请求正文的对象。我认为你想要实现的目标是:

@POST(LiveDataApi.POST_LOGIN)
Flowable<HttpCustomRes<User>> loginUser(@Body UserBody user);

UserBody对象,我想这会是这样的:

class UserBody {
   private final String user;
   private final String password;

   UserBody(String user, String password) {
       this.user = user;
       this.password = password;
   }
}

我建议您阅读Retrofit docs哪里可以更好地解释如何提出正确的请求。