【发布时间】:2014-12-01 06:22:45
【问题描述】:
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));
}
来自服务器的响应是 Json 格式存储在 httpresponse 中,我们获取实体并将其放入 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();
}
EntityUtils.toString(entity) 的输出是 JSON 格式
{"self":"http://localhost:8080/rest/api/latest/user?username=vgupta","name":"vgupta","loginInfo":{"loginCount":55,"previousLoginTime":"2014-12-01T11:39:43.883+0530"}}
并在 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)
如何摆脱这个错误。
如果我想在文件中写入 JSON。
【问题讨论】:
-
entity 是接收 json 内容的 http 实体
-
文件 fJsonFile = new 'File("C:\\Users\\Ashish\\Desktop\\filename.json");'应该在 try 块内。已经试过了,还是不行
-
查看堆栈跟踪,似乎涉及 zip 功能。你能指定堆栈跟踪指向哪一行代码吗?
-
请向我们展示与此代码块相关的
entity的所有用法。 -
您可以使用适当的详细信息编辑您的问题。
标签: java json file ioexception writer