Karate ApacheHttpClient 响应失败,并出现错误 com.intuit.karate - Runtimejava.io.IOException:尝试从关闭的流中读取

问题描述 投票:0回答:1

参考:java.io.IOException:尝试从关闭的流中读取

参考:https://github.com/karatelabs/karate/blob/master/karate-core/src/main/java/com/intuit/karate/http/ApacheHttpClient.java

KarateCore - 类文件:ApacheHttpClient.java 无法处理响应,其在代码行失败

CloseableHttpClient client = clientBuilder.build();
CloseableHttpResponse httpResponse;
byte [] bytes;
try {
            httpResponse = client.execute(requestBuilder.build());
            HttpEntity responseEntity = httpResponse.getEntity();
            if (responseEntity == null || responseEntity.getContent() == null) {
                bytes = Constants.ZERO_BYTES;
            } else {
                **InputStream is = responseEntity.getContent();**
                bytes = FileUtils.toBytes(is);
            }
            request.setEndTimeMillis(System.currentTimeMillis());
        } catch (Exception e) {
            if (e instanceof ClientProtocolException && e.getCause() != null) { // better error message                
                throw new RuntimeException(e.getCause());
            } else {
                throw new RuntimeException(e);
            }
        }

代码在 InputStream is = responseEntity.getContent(); 行失败当尝试从关闭的流中读取时。显示异常信息 错误 com.intuit.karate - Runtimejava.io.IOException:尝试从关闭的流中读取。

可能是InputStream需要更新。

我可以使用下面的代码读取 Http 响应内容

BufferedReader br = new BufferedReader(
                           new InputStreamReader((httpResponse.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null){
      output = br,readLine();
      System.out.println(output);
}

还能够使用 EntityUtils 作为字符串内容读取响应

String content = EntityUtils.toString(responseEntity);
System.out.println(content);

不确定我是否在功能中遗漏了某些内容:场景文件响应或 ApacheHttpClient.java 文件需要更新以读取 InputStream 然后转换为字节。

Feature: Hello
Scenario: Rest API Post
Given url 'some url path'
And header Content-Type = 'application/json'
And request { username: 'abc', password: 'pwd' }
When method POST
Then status 200
And print 'Response is:', response

预期的响应是 JSON 格式:

{
  "accessToken": "akjdoioikf",
  "expires":"2020-01-29T01:09:48Z"
}

任何建议,不胜感激!

rest httpresponse karate
1个回答
0
投票

就我而言,为了解决类似的问题,我更新了 pom 文件:

已更换

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.13</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>io.karatelabs</groupId>
    <artifactId>karate-junit5</artifactId>
    <version>1.5.0</version>
    <scope>test</scope>
</dependency>

希望有帮助

© www.soinside.com 2019 - 2024. All rights reserved.