在使用httprequest过程中遇到一个问题
com.github.kevinsawicki.http.HttpRequestjava.io.IOException: stream is closed
百度查找原因是I/O流只能读取一次,重复读取会导致异常
目前找到两种解决方案:
1、从根本解决:让它可以被多次重复读取
https://blog.csdn.net/zhibo_lv/article/details/81875705
2、只读取一次,将值写入变量,后续使用不再读取HttpRequest
事发代码:
/**
* contentType为json的post请求
*/
public LctBaseResponse PostHttpRequest(URL requestUrl, String body, String cookie, String headers) {
LctBaseResponse response = new LctBaseResponse();
HttpRequest httpRequest ;
HashMap headersMap = JSON.parseObject(headers, HashMap.class);
try {
logger.info("POST请求开始:" + "requestUrl=" + requestUrl + "cookie=" + cookie + "headers=" + headers);
httpRequest =
HttpRequest.post(requestUrl).header("Cookie", cookie)
.contentType(HttpRequest.CONTENT_TYPE_JSON)
.headers(headersMap).send(body);
if (httpRequest.body() == null || httpRequest.code() == 500){
throw new InsurCoreException(ErrorCode.CLIENT_ERROR);
}
logger.info("返回结果: " + httpRequest.body());
response.setCode(Integer.toString(httpRequest.code()));
response.setData(httpRequest.body());
}catch (Exception e){
logger.error("调用失败: " + e);
throw new InsurCoreException(ErrorCode.CLIENT_ERROR);
}
return response;
}
- 因为多次执行了
httpRequest.body()
导致报错
在尝试定位异常时,在这里打了断点,并在控制台打出了内容,控制台展示的返回正常,实际执行时又报错,当时极端想不明白,后来才明白,在第二次执行时I/O流已经关闭,再次读取时就出现流报错。
使用方法2处理后的代码
/**
* contentType为json的post请求
*/
public LctBaseResponse PostHttpRequest(URL requestUrl, String body, String cookie, String headers) {
LctBaseResponse response = new LctBaseResponse();
HttpRequest httpresult ;
HashMap headersMap = getHeaders(headers);
try {
logger.info("POST请求开始:requestUrl= {} body= {}" + requestUrl, body);
httpresult =
HttpRequest.post(requestUrl).header("Cookie", cookie)
.contentType(HttpRequest.CONTENT_TYPE_JSON)
.headers(headersMap).send(body);
String result = httpresult.body();
if (result == null || httpresult.code() == 500){
throw new LcToolsException(ErrorCode.CLIENT_ERROR);
}
logger.info("返回结果: " + result);
response.setCode(Integer.toString(httpresult.code()));
response.setData(result);
}catch (Exception e){
logger.error("调用失败: " + e);
throw new LcToolsException(ErrorCode.CLIENT_ERROR);
}
return response;
}```
网友评论