java.io.IOException: Attempted read from closed stream


前言:

代碼如下,執行的時候提示“java.io.IOException: Attempted read from closed stream.”

public static JSONObject post(String url,StringBuffer params,String token ){

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url + "?" + params);
        httpPost.setHeader("Content-Type", "application/json, text/plain, */*");
        httpPost.setHeader("Authorization",token);

        // 響應模型
        CloseableHttpResponse response = null;
        try {
            // send the Post Request
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
           if (responseEntity != null) {
                System.out.println("響應內容長度為:" + responseEntity.getContentLength());
                System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
                String jsonString = EntityUtils.toString(responseEntity);
                resBody = JSONObject.fromObject(jsonString);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //release resource
            release(httpClient,response);
        }
        return resBody;
    }

原因

response.getEntity()所得到的流是不可重復讀取的,所得的實體只能讀取一次,讀取一次后,流就關閉了。EntityUtils.toString(responseEntity)被調用一次后就會自動銷毀,而我調用了2次,所以就報錯了。

System.out.println("響應內容為:" + EntityUtils.toString(responseEntity));
String jsonString = EntityUtils.toString(responseEntity);

解決方法

把這2個輸出腳本改為如下即可,只要調用一次就好:

  String jsonString = EntityUtils.toString(responseEntity);
  System.out.println("響應內容為:" + jsonString);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM