java中调用request报错,使用httprequest时HttpRequestjava.io.IOException

在使用httprequest过程中遇到一个问题

com.github.kevinsawicki.http.HttpRequestjava.io.IOException: stream is closed

百度查找原因是I/O流只能读取一次,重复读取会导致异常

目前找到两种解决方案:

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;

}```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值