How do I convert an InputStream into a String in Java?

To read an InputStream into a String in Java, you can use the BufferedReader class. Here’s an example of how you can do this:

StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

String line;
while ((line = reader.readLine()) != null) {
    result.append(line);
}

String resultString = result.toString();

This reads each line of the InputStream using the readLine method of the BufferedReader and appends it to a StringBuilder. After the InputStream has been completely read, the StringBuilder is converted to a String using the toString method.

Alternatively, you can use the IOUtils class from the Apache Commons IO library, which has a toString method that can read an InputStream into a String:

String resultString = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

This method reads the entire InputStream into memory at once, so it may not be suitable for very large streams.