gpt4 book ai didi

java - 以 json 格式写入文件时出错。Stream 已关闭

转载 作者:行者123 更新时间:2023-11-29 05:14:03 31 4
gpt4 key购买 nike

      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。

最佳答案

这似乎没有在 javadoc 中指定,但是 EntityUtils.toString(HttpEntity) 关闭了 HttpEntityInputStream。由于您使用相同的 HttpEntity 两次调用该方法,因此第二次它已经关闭。

不是调用它两次,而是存储结果

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

并在其他地方重用内容

关于java - 以 json 格式写入文件时出错。Stream 已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27222771/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com