我有一段代码,它使用 RxJava zip()
运算符同时对我的 REST API 执行两个独立的调用:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Observable<List<Player>> obs_players = RestAPI.getApi().getService()
.getAllPlayers(LoggedUser.getInstance().getToken());
Observable<List<Game>> obs_games = null;
// first id corresponds to ALL players
if (id == 0){
obs_games = RestAPI.getApi().getService()
.getAllGames();
}
// get the player's id
else{
int player_id = (int)liste_players.get((int)id - 1).getId();
obs_games = RestAPI.getApi().getService().getGamesSingleUser(player_id);
}
// Parallely get all users and required games to be displayed
Observable<Pair<List<Game>, List<Player>>> obs_combined = null;
obs_combined.zip(obs_games, obs_players, (l_g, l_p)->
new Pair<>(l_g, l_p))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Pair<List<Game>, List<Player>>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.d("DBG", "onSubscribe - onItemSelected");
}
@Override
public void onNext(@NonNull Pair<List<Game>, List<Player>> listListPair) {
Log.d("DBG", "onNext - onItemSelected");
// loop over games
for (Game g: listListPair.first){
// loop over PlayerInGame
for (PlayerInGame pig: g.getListe_joueurs()){
pig.setPlayer(
Collections2.filter(listListPair.second,
player-> player.getId()==pig.getPlayer()
.getId())
.iterator()
.next()
);
}
}
liste_match = listListPair.first;
expandable_list_adapter.setData(liste_match);
expandable_list_adapter.notifyDataSetChanged();
}
@Override
public void onError(@NonNull Throwable e) {
Log.d("", "onError");
}
@Override
public void onComplete() {
Log.d("DBG", "onComplete - onItemSelected");
}
});
虽然它的工作没有引发任何错误,但在服务器端,我注意到与 obs_games
相关的 GET
方法被调用了两次,第二次成功:
[27/Sep/2017 20:49:01] "GET /users/3/games HTTP/1.1" 301 0
[27/Sep/2017 20:49:01] "GET /users/3/games/ HTTP/1.1" 200 537
[27/Sep/2017 20:49:01] "GET /users/ HTTP/1.1" 200 451
我已经检查过 onSubscribe()
、onNext()
和 onComplete()
方法被调用一次,所以我不知道在哪里调用这个问题可能来自于。
最佳答案
HTTP 响应代码 301 是重定向。
您的客户端代码正在调用服务来获取“/users/3/games”。在服务器端,某些东西(可能是代码周围的框架)正在识别路径不正确。作为目录,框架需要尾随“/”。
因此服务器发回 301,表明您想要的内容已“移动”到“/users/3/games/”(注意结尾的“/”)。
此时,客户端(可能是您正在使用的框架/接口(interface))发现地址已更改,并向服务器发出另一个 GET(使用正确的地址)。
在第二次调用时,执行预期的服务器端函数,并响应 200(成功)。
关于java - GET 方法调用两次,代码为 301 和 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46457117/