错误:Attempted read from closed stream尝试读取关闭的流!!!

在这里插入图片描述

原因:一个HttpClient里只能有一次获取Entity的操作,不能有多次获取Entity的操作,getEntity()获取的流是一次性的,用了一次就会自动关闭,第二次调用的时候就是调一个关闭的流,就会抛出:Attempted read from closed stream;

解决办法:如果一个方法只对同一个Entity操作,可以用BufferedHttpEntity,可以多次读取流!

HttpEntity entity = httpResponse.getEntity();
 if (!Objects.isNull(entity)) {
   try {
    //entity实体流保存缓冲区,否则只能操作一次流就会关闭 ,BufferedHttpEntity可以多次读取流
    entity = new BufferedHttpEntity(entity);
    responseBody = URLEncodedUtils.parse(entity).toString();
    } catch (IOException e) {
      e.printStackTrace();
      LogUtils.error(e, log, "io转换错误");
   }
 }

如果一个方法只对不同一个Entity操作,可以用一个临时的变量接收获取的Entity,再用临时变量走后续的逻辑!!!

这是没用临时变量接收之前,运行报错:Attempted read from closed stream

private static String getRemoteCallLogStr(HttpUriRequest httpUriRequest, HttpResponse httpResponse, long start, String method, Exception ex, String siteName) {
        String startTime = DateFormatUtils.format(new Date(start), "yyyy-MM-dd'T'HH:mm:ss.SSS");
        String path = "";
        String targetUrl = "";
        String uri = "";
        String targetHost = "";
        String requestheader = "";
        String responseHeader = "";
        String responseBody = "";
        Integer responseStatus = null;
        if (!Objects.isNull(httpUriRequest)) {
            if (!Objects.isNull(httpUriRequest.getURI())) {
                path = httpUriRequest.getURI().getPath();
                targetUrl = httpUriRequest.getURI().toString();
                targetHost = httpUriRequest.getURI().getHost();
                uri = httpUriRequest.getURI().toString();
            }
            requestheader = JSON.toJSONString(httpUriRequest.getAllHeaders());
        }
        if (!Objects.isNull(httpResponse)) {
            if (!Objects.isNull(httpResponse.getStatusLine())) {
                responseStatus = httpResponse.getStatusLine().getStatusCode();
            }
            HttpEntity entity = httpResponse.getEntity();
            if (!Objects.isNull(entity)) {
                try {
                    responseBody = URLEncodedUtils.parse(entity).toString();
                    System.out.println(responseBody);
                } catch (IOException e) {
                    LogUtils.error(e, log, "io转换错误");
                }
            }
            responseHeader = JSON.toJSONString(httpResponse.getAllHeaders());
        }
        RemoteCallLog content = RemoteCallLog.builder()
                .type("remote")
                .loggerName(HttpsUtils.class.getName())
                .level(ex == null ? "INFO" : "ERROR")
                .logId(LogUtils.getLogId())
                .time(startTime)
                .hostName(EnvironmentUtil.getHostName())
                .targetMethod(path)
                .targetUrl(targetUrl)
                .requestId(LogUtils.initRequestIdIfAbsent())
                .uri(uri)
                .requestMethod(method)
                .status(ex == null ? "success" : "fail")
                .duration(System.currentTimeMillis() - start)
                .requestHeader(requestheader)
                .responseBody(responseBody)
                .responseHeader(responseHeader)
                .stackTrace(ex == null ? "" : ExceptionUtils.getFullStackTrace(ex))
                .build();
        if ("POST".equals(method)) {
            content.setTargetSystem(siteName);
        } else {
            content.setTargetSystem(targetHost);
        }
        if (!Objects.isNull(responseStatus)) {
            content.setResponseStatus(responseStatus);
        }
        if ("GET".equals(method) && !Objects.isNull(httpUriRequest) && !Objects.isNull(httpUriRequest.getURI())) {
            content.setRequestUrlParam(httpUriRequest.getURI().getQuery());
        } else {
            HttpPost httpPost = (HttpPost) httpUriRequest;
            HttpEntity entity =  httpPost.getEntity();
            try {
              content.setRequestBodyParam(URLEncodedUtils.parse(entity).toString());
                System.out.println(content.getRequestBodyParam());
            } catch (IOException e) {
                LogUtils.error(e, log, "io转换错误");
                e.printStackTrace();
            }
        }
        return JSONObject.toJSONString(content);
    }

加了临时变量之后,就没有抛:Attempted read from closed stream!

HttpEntity temp=null;
HttpEntity entity = httpResponse.getEntity();
temp=entity;
if (!Objects.isNull(entity)) {
  try {
    responseBody = URLEncodedUtils.parse(temp).toString();
  } catch (IOException e) {
    e.printStackTrace();
    LogUtils.error(e, log, "io转换错误");
  }
}
HttpEntity requestTemp=null;
HttpPost httpPost = (HttpPost) httpUriRequest;
HttpEntity entity =  httpPost.getEntity();
requestTemp=entity;
try {
  content.setRequestBodyParam(URLEncodedUtils.parse(requestTemp).toString());
} catch (IOException e) {
  e.printStackTrace();
  LogUtils.error(e, log, "io转换错误");
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐