error writing in a file in json format.Stream closed

2.9k views Asked by At
      HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
          getRequest.setHeaders(headers);
          HttpHost target = new HttpHost("localhost", 8080, "http");
          HttpPost postRequest = new HttpPost("/rest/auth/1/session/");
          System.out.println("executing request to "+target +getRequest);
          HttpResponse httpResponse = httpclient.execute(target,postRequest);
          HttpEntity entity = httpResponse.getEntity();
          if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
          }

the response from servers is in Json format is stored in httpresponse and we get the entity and put it in httpentity

 File fJsonFile = new File("C:\\Users\\Ashish\\Desktop\\filename.json");
              try {
                    // if file doesnt exists, then create it
                    if (!fJsonFile.exists()) {
                        fJsonFile.createNewFile();
                    }
                    FileWriter fw = new FileWriter(fJsonFile.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(EntityUtils.toString(entity));
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

Output of EntityUtils.toString(entity) is in JSON format

{"self":"http://localhost:8080/rest/api/latest/user?username=vgupta","name":"vgupta","loginInfo":{"loginCount":55,"previousLoginTime":"2014-12-01T11:39:43.883+0530"}}

and following exception at line bw.write(EntityUtils.toString(entity));

java.io.IOException: Stream closed
at java.util.zip.GZIPInputStream.ensureOpen(Unknown Source)
at java.util.zip.GZIPInputStream.read(Unknown Source)
at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:74)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.Reader.read(Unknown Source)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:244)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:288)
at jira.JiraGetPostDeleteReq.main(JiraGetPostDeleteReq.java:68)

how to get rid of this error.

If I want to write JSON in a file.

1

There are 1 answers

1
Sotirios Delimanolis On BEST ANSWER

This doesn't seem to be specified in the javadoc, but EntityUtils.toString(HttpEntity) closes the HttpEntity's InputStream. Since you're invoking the method twice with the same HttpEntity, the second time it is already closed.

Instead of invoking it twice, store the result

String content = null;
if (entity != null) {
    content = System.out.println(EntityUtils.toString(entity));
}

and reuse content everywhere else.