【问题标题】:Apache http write response to fileApache http 对文件的写入响应
【发布时间】:2016-06-15 16:09:27
【问题描述】:

我正在尝试将 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)

【问题讨论】:

    标签: java file http response inputstream


    【解决方案1】:

    其他人在另一个论坛上回答了您的问题: java.io.IOException: Attempted read from closed stream

    我有同样的问题;我为相同的内容两次致电response.getEntity()。一旦我注释掉了第二个电话,一切都开始运转良好。

    这里是文档的链接: http://hc.apache.org/httpcomponents-core-4.2.x/httpcore/apidocs/org/apache/http/HttpEntity.html#getContent%28%29

    【讨论】:

      【解决方案2】:

      我不确定这是否是答案,但您需要先将响应信息设置为新类。我使用 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();
      }
      

      【讨论】:

        猜你喜欢
        • 2016-04-23
        • 2015-06-29
        • 1970-01-01
        • 2012-08-08
        • 1970-01-01
        • 1970-01-01
        • 2018-07-08
        • 1970-01-01
        • 2019-01-29
        相关资源
        最近更新 更多