0

I am using REST API. I have below code snippet :

conn = (HttpURLConnection) url.openConnection();
                       OutputStream outputstream = conn.getOutputStream(); 
                       if (payload.getString("phase_id") != null) {
                        bodyParam = new JSONObject();
                        bodyParam.put("phase_id", payload.getString("phase_id"));
                        outputstream.write(bodyParam.toString().getBytes());
                    }
                    logger.info(""+outputstream);
                    outputstream.flush();
                    if (payload.getString("subphase_id") != null) {
                        bodyParam = new JSONObject();
                        bodyParam.put("subphase_id", payload.getString("subphase_id"));
                        outputstream.write(bodyParam.toString().getBytes());
                    }
                    logger.info(""+outputstream);

Here ,even i am flushing th outputstream it gives me output like :

{"phase_id":101}
{"phase_id":101}{"subphase_id":201}

But i want output like :

{"phase_id":101}
{"subphase_id":201}

My concern is ,even i am flushing data then why it is giving previous data ? Is something i am missing ?

Neha
  • 109
  • 3
  • 15
  • Does this answer your question? [What is the purpose of flush() in Java streams?](https://stackoverflow.com/questions/2340106/what-is-the-purpose-of-flush-in-java-streams) – Attila jáger Jul 31 '20 at 10:41
  • Thanks for response but even i used flush then why it show duplicate data , is it something with conn.getinputstream ? if yes then what shoulf i do in that case ? – Neha Jul 31 '20 at 10:54

2 Answers2

0

It doesn't show duplicate data you just log twice.

The Java OutputStream's flush() method flushes all data written to the OutputStream to the underlying data destination. For instance, if the OutputStream is a FileOutputStream then bytes written to the FileOutputStream may not have been fully written to disk yet. The data might be buffered in OS memory somewhere, even if your Java code has written it to the FileOutputStream. By calling flush() you can assure that any buffered data will be flushed (written) to disk (or network, or whatever else the destination of your OutputStream has).

link. I think you want to clear your OutputStream before writing again but that's not what flush does.

0

Flush method doesn't clear the data that you have already written to the stream. You need to close it and create a new OutPutStream then write in it.