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,Object> map,Class<T> clazz){ RestTemplate restTemplate = new RestTemplate(); ResponseEntity<T> responseEntity = restTemplate.getForEntity(url,clazz,map); return responseEntity.getBody(); } /** * https://www.programcreek.com/java-api-examples/index.php?class=org.springframework.web.client.RestTemplate&method=postForEntity * @param url 请求的结果 * @param map 请求参数 * @param clazz 返回结果类型 * @param <T> * @return */ public static <T> T post(String url, MultiValueMap
,Object> map, Class<T> clazz){ RestTemplate restTemplate = new RestTemplate(); ResponseEntity<T> responseEntity = restTemplate.postForEntity(url,map,clazz); return responseEntity.getBody(); } /** * 各種請求 * https://www.programcreek.com/java-api-examples/index.php?class=org.springframework.web.client.RestTemplate&method=exchange *
* HttpHeaders headers = new HttpHeaders(); * headers.add("access","token"); * MultiValueMap ,Object> map = new LinkedMultiValueMap<>(); * map.add("username","rwrwer"); * HttpEntity ,Object>> entity = new HttpEntity<>(map,headers); * String content = RestUtil.exchange(url, HttpMethod.POST,entity,String.class); * * @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(); } }