在HttpClient请求的时候,返回结果解析时出现java.io.IOException: Attempted read from closed stream. 异常,解决

HttpClient中的请求,一个方法中只能请求一次。

解决方案:

在springBoot中使用restTemplate的方法:

工具类:

/**
 * @author xwolf
 * @since 1.8
 **/
public class RestUtil {
    /**
     * get 请求
     * @param url 请求的url
     * @param map  参数
     * @param clazz 返回结果类型
     * @param <T>
     * @return
     */
    public static <T> T get(String url, Map<String,Object> map,Class<T> clazz){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> responseEntity = restTemplate.getForEntity(url,clazz,map);
        return responseEntity.getBody();
    }

    /**
     * <code>https://www.programcreek.com/java-api-examples/index.php?class=org.springframework.web.client.RestTemplate&method=postForEntity</code>
     * @param url 请求的结果
     * @param map   请求参数
     * @param clazz  返回结果类型
     * @param <T>
     * @return
     */
    public static <T> T post(String url, MultiValueMap<String,Object> map, Class<T> clazz){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url,map,clazz);
        return responseEntity.getBody();
    }


    /**
     * 各種請求
     * <code>https://www.programcreek.com/java-api-examples/index.php?class=org.springframework.web.client.RestTemplate&method=exchange</code>
     * <example>
     * HttpHeaders headers = new HttpHeaders();
     * headers.add("access","token");
     * MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
     * map.add("username","rwrwer");
     * HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity<>(map,headers);
     * String content = RestUtil.exchange(url, HttpMethod.POST,entity,String.class);
     * </example>
     * @param url
     * @param httpMethod
     * @param httpEntity
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T exchange(String url, HttpMethod httpMethod,HttpEntity<?> httpEntity,Class<T> clazz){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> responseEntity =  restTemplate.exchange(url,httpMethod,httpEntity,clazz);
        return responseEntity.getBody();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值