gpt4 book ai didi

java - EntityUtils.toString 进入 IOException

转载 作者:行者123 更新时间:2023-12-01 12:13:22 25 4
gpt4 key购买 nike

在以下代码中,EntityUtils.toString 将进入 IOException。当我将 'EntityUtils.toString(entity)' 粘贴到 Eclipse 监 window 口上时,它显示了已禁用的值

private String triggerRestApiCalls(String url){
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
getRequest.setHeader(
new BasicHeader("Accept", "application/json"));
try {
HttpResponse response = httpClient.execute(getRequest);
HttpEntity entity = response.getEntity();
String value = EntityUtils.toString(entity);
return value;

} catch (ClientProtocolException e) {
log.debug(e.getCause());
} catch (IOException e) {
log.debug(e.getCause());
}
log.debug("Status Unknown");
return "UNKNOWN";
}

内容值长度为 8。预期的字符串为 DISABLED,正好是长度。 HTTP 状态为 200(正常)。

我使用了具有相同 URL 的curl。

curl -i   -H {Accept: application/json} http://127.0.0.1:9031/test/test.html?someDetails
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=D35C61744F4FB3A47B624FF3D0BEB026; Path=/mics/; Secure; HttpOnly
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 8
Date: Wed, 26 Nov 2014 13:23:30 GMT

已禁用。

感谢任何帮助!编码有什么角度吗?

第一次编辑

堆栈跟踪提到了这一点。

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

EntityUtils.toString()执行的代码

  public static String toString(
final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}

我已经完成了这个步骤并且没有错误但是,它在返回之前关闭了流。但返回的实际值是 CharArrayBuffer,它未链接到流。相同的代码可以在其他一些 java 文件中运行。奇怪的 !!我正在使用 Spring ..有 Spring 角度吗?

最佳答案

HttpEntity 只能读取一次,并且似乎有其他东西正在拦截并读取响应,因此当您尝试应用 EntityUtils.toString() 时,您会收到此异常。我不明白为什么会发生这种情况,尽管您确实提到可能存在 Spring 角度,因此此处可能应用了 Spring 拦截器。

你可以试试

String value = httpClient.execute(getRequest, new BasicResponseHandler());

尽管从我看来,这应该与上面的代码相当等效。

关于java - EntityUtils.toString 进入 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27150434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com