spingBoot RestTemplate get和post请求封装
public ResponseEntity<String> sendParamsMapForResponseEntity(String url, HttpMethod httpMethod, Map<String, String> headersMap, Map<String, Object> paramsMap) { HttpHeaders httpHeaders = null; if (MapUtils.isNotEmpty(headersMap)) { httpHeaders = new HttpHeaders(); for (Map.Entry<String, String> entry : headersMap.entrySet()) { httpHeaders.add(entry.getKey(), entry.getValue()); } } StringBuffer urlStringBuffer = new StringBuffer(url); HttpEntity<Object> httpEntity = null; if (HttpMethod.GET.equals(httpMethod)) { if (MapUtils.isNotEmpty(paramsMap)) { urlStringBuffer.append("?"); int index = 0; for (Map.Entry<String, Object> entry : paramsMap.entrySet()) { if (index == 0) { urlStringBuffer.append(entry.getKey()).append("=").append(entry.getValue()); } else { urlStringBuffer.append("&").append(entry.getKey()).append("=").append(entry.getValue()); } index++; } } httpEntity = new HttpEntity<Object>(httpHeaders); } else { if (MapUtils.isNotEmpty(headersMap) && MediaType.APPLICATION_JSON_VALUE.equals(headersMap.get(HttpHeaders.CONTENT_TYPE))) { httpEntity = new HttpEntity<Object>(JSON.toJSONString(paramsMap), httpHeaders); } else { httpEntity = new HttpEntity<Object>(paramsMap, httpHeaders); } } ResponseEntity<String> responseEntity = baseRestTemplate.exchange(urlStringBuffer.toString(), httpMethod, httpEntity, String.class); return responseEntity; }
spingBoot RestTemplate get和post请求封装