您的位置:首页 > 理论基础 > 计算机网络

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

2018-01-25 16:33 1896 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐