我正在尝试将org.apache.http.HttpResponse写入档案。
System.out.println("length");
System.out.println(EntityUtils.toByteArray(response.getEntity()).length);
给出这个: 长度 48905367
OutputStream outputStream = new FileOutputStream(new File("C:/response.json"));
org.apache.commons.io.IOUtils.copy(response.getEntity().getContent(), outputStream);
outputStream.close();
给出了这个
Exception in thread "main" java.io.IOException: Attempted read from closed stream.
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:179)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:150)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1025)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:999)
答案 0 :(得分:1)
我不确定这是否是答案,但您需要先将响应信息设置为新类。我使用Gson库:
Gson gson = new Gson();
HttpResponse response = httpGetRequest("URL_ENDPOINT");
ResponseDTO responseDTO = gson.fromJson(prettyJsonResponse(response),
ResponseDTO.class);
这是http get请求方法:
private HttpResponse httpGetRequest(String url) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
return client.execute(request);
}
这是maven的依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
prettyJsonResponse方法:
private String prettyJsonResponse(HttpResponse response) throws IOException{
StringBuffer result = new StringBuffer();
String line = "";
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
答案 1 :(得分:-1)
其他人在另一个论坛上回答了您的问题: java.io.IOException: Attempted read from closed stream
我有同样的问题;我在同一内容中两次致电response.getEntity()
。一旦我评论了第二个电话,一切都开始运作良好。