tt0686
tt0686

Reputation: 1849

InputStream reading

Good night in my timezone.

I am building an http bot, and when i receive the response from the server i want to make two things.First is to print the body of the response and because i know that the body of the response is of the type TEXT/HTML the second thing that i make is to parse the response through a html parser(in this specific case NekoHtml). Snippet of code :

    //Print the first call
    printResponse(urlConnection.getInputStream());
    document = new InputSource(urlConnection.getInputStream());
    parser.setDocument(document);

The problem is when i run the first line (printResponse) the second line will throw an exception. Now the questions-> This happens because the InputStream can only be read one time ?every time that we read from the inputstream the bytes are cleaned? How can we read more that one time the content from the inputstream ?

Thanks in advance

Best regards

Upvotes: 0

Views: 2631

Answers (3)

maks
maks

Reputation: 6006

As Ted Hopp said:

    byte [] bytes = new byte[urlConnection.getInputStream().available()];
    printResponse(new ByteArrayInputStream(bytes));
    document = new InputSource(new ByteArrayInputStream(bytes));
    parser.setDocument(document);

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

In addition to what Ted Hopp said take a look at Apache Commons IO library. You will find:

  • IOUtils.toString(urlConnection.getInputStream(), "UTF-8") utility method that takes an input stream, fully reads it and returns a string in a given encoding

  • TeeInputStream is an InputStream decorator that takes will copy every read byte and copy it into a given output stream as well.

Should work:

 InputStream is = new TeeInputStream(urlConnection.getInputStream(), System.out);

Upvotes: 5

Ted Hopp
Ted Hopp

Reputation: 234795

Read the response from the server into a byte array. You can then create a ByteArrayInputStream to repeatedly read the bytes.

Upvotes: 0

Related Questions