2017-06-19 38 views
1

我正試圖學習RxJava2和Retrofit,現在我知道如何調用GET請求。但我不知道該怎麼做,POST,PUT ...等如何使用RxJava2和Retrofit2做POST請求?

我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

首先,我鼓勵您使用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哪裏比較好解釋瞭如何做出適當的要求。