简体   繁体   中英

Java Retrofit multiple request one single response

Hello guys I have an api endpoint that only takes one parameter "name": https://api.xxxxx.com/v1/test/ {name}/

I'm stuck on making a multiple request (eg https://api.xxxxx.com/v1/test/ALEX/ , https://api.xxxxx.com/v1/test/ELISA/ , https://api.xxxxx.com/v1/test/JOE/ )

I need to parse all the data from those 3 calls in a recyclerview, each request in a different row.

Is there anyway I can make the 3 request then get 1 JSON response only so I can parse it? What would be the best approach to accomplish this?

I assume you have something like the following code in your retrofit api interface

@GET("v1/test/{name}/")
Observable<UserModel> getUserBy(@Path("name") name) 

Then in your business logic you can call.

Observable.zip(retrofitApi.getUser("ALEX"), retrofitApi.getUser("ELISA"), retrofitApi.getUser("JOE"), (u1, u2, u3) -> {
  // prepare your returned users in a way suitable for further consumption
  // in this case I put them in a list
  return Arrays.asList(u1, u2, u3);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe( listOfUsers -> // TODO: do something with your users)

Hope this helps.

create an Interface like this

@FormUrlEncoded
@POST("/locations/add.json")
void sendMultipleLocations(@Query("token")String token, @FieldMap List<Map<String, String>> multipleLocations, Callback<String> callback);

and use enqueue method of retrofit2 for asynchronously calling multiple request at the same time.This link will help you

https://github.com/square/retrofit/issues/1517

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM