Java Apache http文件写入响应
我正在尝试将org.apache.http.HttpResponse写入文件Java Apache http文件写入响应,java,file,http,response,inputstream,Java,File,Http,Response,Inputstream,我正在尝试将org.apache.http.HttpResponse写入文件 System.out.println("length"); System.out.println(EntityUtils.toByteArray(response.getEntity()).length); 给出了: 长度 48905367 给这个 Exception in thread "main" java.io.IOException: Attempted read from closed stream.
System.out.println("length");
System.out.println(EntityUtils.toByteArray(response.getEntity()).length);
给出了:
长度
48905367
给这个
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)
其他人在另一个论坛上回答了您的问题: 我也有同样的问题;我为同一内容调用了两次
response.getEntity()
。当我评论完第二个电话后,一切都开始运转良好
以下是文档的链接:
我不确定这是否是答案,但您需要先将响应信息设置为new class。我使用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>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
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();
}