Ad

How To Just Read First N Lines Of A GET API Response Instead Of Loading The Entire Response?

- 1 answer

We have a GET API and the response is a huge list of certificates. How do we read just the 1st certificate if we know the start and end tag of the 1st certificate? instead of loading the entire response in the memory?

Sample Response :
--------Start Certificate 1---------
chgdbhbdjnjkvfdlnlkvdknl;vkkdsnvnknv
hvjbdjnjvnjdnvjkndjvnjdnvjndnvdjbdee
hbvhjfbnvjnbjfnvjnfjnvjnfjvjnvfjnvjd
---------End Certificate 1----------
--------Start Certificate 2---------
chgdbhbdjnjkvfdlnlkvdknl;vkkdsnvnknv
hvjbdjnjvnjdnvjkndjvnjdnvjndnvdjbdee
hbvhjfbnvjnbjfnvjnfjnvjnfjvjnvfjnvjd
---------End Certificate 2----------
--------Start Certificate 3---------
chgdbhbdjnjkvfdlnlkvdknl;vkkdsnvnknv
hvjbdjnjvnjdnvjkndjvnjdnvjndnvdjbdee
hbvhjfbnvjnbjfnvjnfjnvjnfjvjnvfjnvjd
---------End Certificate 3----------
--------Start Certificate 4---------
chgdbhbdjnjkvfdlnlkvdknl;vkkdsnvnknv
hvjbdjnjvnjdnvjkndjvnjdnvjndnvdjbdee
hbvhjfbnvjnbjfnvjnfjnvjnfjvjnvfjnvjd
---------End Certificate 4----------
Ad

Answer

Using the provided sample, you can do it like this:

    //getting the input stream as a project resource
    //you should get it from the API response
    InputStream inputStream = Objects.requireNonNull(ClassLoader.getSystemResourceAsStream("response.txt"));
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final String start = "--------Start Certificate 1---------";
    final String end = "---------End Certificate 1----------";
    String line = reader.readLine();
    //dumping everything before first certificate start
    while (!line.equals(start)) {
      line = reader.readLine();
    }
    StringBuilder firstCertificate = new StringBuilder(line).append(System.lineSeparator());
    line = reader.readLine();
    while (!line.equals(end)) {
      firstCertificate.append(line).append(System.lineSeparator());
      line = reader.readLine();
    }
    firstCertificate.append(line);
    System.out.println(firstCertificate);

If you or your team are responsible for this API, it would be best if you add support for pagination. If you happen to need second, third certificate, or something after that, you still have to read up to that. And there is no point in the server sending data you will just dump.

Ad
source: stackoverflow.com
Ad