2

I have gotten HttpURLConnection inputStream:

    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    InputStream stream = conn.getInputStream();

Now I want to produce two copy of this inputStream, one is used to store to a file, and the other one is used to parse, but after I stored, the inputStream is invalid to parse:

        BufferedInputStream bis = new BufferedInputStream(inStream);
        try {
            byte[] buffer = new byte[1024];

            if (inStream.markSupported()) {
                inStream.mark(1);                   
            }
            int bytesRead = 0;
            while ((bytesRead = bis.read(buffer)) != -1) {
                Log.d(TAG, "buffer: "+new String(buffer));
                outStream.write(buffer, 0, bytesRead);
            }
            outStream.flush();
            inStream.reset();
            outStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

Now how to get this inputStream entirely again?

Victor S
  • 4,021
  • 15
  • 43
  • 54

2 Answers2

3

Use http://commons.apache.org/proper/commons-io/ Commons-IO to get a byte[] of the data in the InputStream

byte[] data = IOUtils.toByteArray(httpsURLConnection.getInputStream());

Then store the data in a file by writing it in an OutputStream, then do with the data whatever you want.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

Now how to get this inputStream entirely again?

You do everything all over again, starting with HttpURLConnection conn = (HttpURLConnection) url.openConnection();.

Or, you do two things with with bytes as you download them, rather than downloading them twice.

Or, you use the stream from HTTP to download to the file, then you read in the file for parsing.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • The http server content changes every second, if get again, it is not the same content. – Victor S Nov 05 '14 at 11:57
  • @VictorS: Then your options are the second and third ones in my answer: do two things with the bytes as you download them (more efficient but perhaps more difficult to code), or read in the file once you save it (easier but adds more disk I/O). – CommonsWare Nov 05 '14 at 11:59