直接上代码:
public class HttpUtils { private static final RestTemplate restTemplate = new RestTemplate(); // Get请求 public static String Get(String url, Map<String, Object> params) { String uri = buildUri(url, params); ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class); return response.getBody(); } // Get请求 public static String Get(String uri) { ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class); return response.getBody(); } // Post请求(JSON请求) public static String JPost(String url, Map<String, Object> params) { HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, jsonHeaderBuilder()); ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); return response.getBody(); }// Post请求(Params) public static String UPost(String url, MultiValueMap<String, String> params) { HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, urlHeaderBuilder()); ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); return response.getBody(); } // 拼接Url和参数 private static String buildUri(String url, Map<String, Object> params) { StringBuilder sb = new StringBuilder(url); sb.append("?"); for (Map.Entry<String, Object> entry : params.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } // 构建Url请求头 private static HttpHeaders urlHeaderBuilder() { HttpHeaders h = new HttpHeaders(); h.setContentType(MediaType.APPLICATION_FORM_URLENCODED); return h; } // 构建Json请求头 private static HttpHeaders jsonHeaderBuilder() { HttpHeaders h = new HttpHeaders(); h.setContentType(MediaType.APPLICATION_JSON); return h; } }