【发布时间】:2015-01-24 20:33:41
【问题描述】:
在以下代码中,EntityUtils.toString 将进入 IOException。当我在 Eclipse 监视窗口上粘贴 'EntityUtils.toString(entity)' 时,它会显示禁用的值
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: Attempted read from closed stream.
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 文件。奇怪的 !!我正在使用弹簧..这个有弹簧角度吗?
【问题讨论】:
-
IOException 的堆栈跟踪?
-
我添加了更多细节。谢谢!