I have to make an HTTP POST request by passing header and body. In the body, I need to provide a pageNumber
before posting data so I am starting with "1" initially. After that I will post data and I will get a JSON response back as shown below.
{ "response": { "pageNumber": 1, "entries": 200, "numberOfPages": 3 }, "list": [ { // some stuff here } ], "total": 1000 }
Now in the above response numberOfPages
are 3 so I need to make a total of three calls to the same URL. Since we already made 1 call I will make 2 more calls with pageNumber
"2" and "3" in the body.
The logic is like this but problem here is that I don't know what is the value for numberOfPages
and I get to know this value after the first call with pageNumber
1.
for(int i=1; i<=numberOfPages; i++) { // call getBody by passing corresponding pageNumber // post data with header and body }
Below is my working code. I just need to call the same URL until numberOfPages
times by just changing the body. For each call, it should be made with the corresponding pageNumber
.
private void collect() { String endpoint = "url_endpoint"; try { final URI uri = URI.create(endpoint); int number = 1; while (true) { HttpEntity<String> requestEntity = new HttpEntity<String>(getBody(number), getHeader()); ResponseEntity<Stuff> responseEntity = HttpClient.getInstance().getClient() .exchange(uri, HttpMethod.POST, requestEntity, Stuff.class); Stuff response = responseEntity.getBody(); // do stuff with response here. int expectedNumber = (int) response.getPaginationResponse().getTotalPages(); if (number == expectedNumber || expectedNumber == 0) { break; } number++; } } catch (Exception ex) { ex.printStackTrace(); } } private String getBody(final int number) { Input input = new Input(entries, number, 0); Body body = new Body("Stuff", input); return gson.toJson(body); }
Is this the right way to do it or is there any better and efficient way?