import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * @description 将RestTemplate注入到容器当中,让他保持单例,当我们哪个类要使用的时候直接从容器里面获取即可。这样可以避免每调用一次创建一个RestTemplate对象 */ @Configuration public class ApplicationContextBean { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
先注入单列模式
http发送get请求和POST2种请求方式
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson2.JSONObject; import com.cdtye.common.core.utils.StringUtils; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.*; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Objects; @Component @Slf4j public class HttpUtils { @Resource private RestTemplate restTemplate; private static HttpUtils httpUtils; @PostConstruct public void init(){ httpUtils = this; httpUtils.restTemplate = this.restTemplate; } public static <T> String sendGetRequest(String url,String token, Map<String, Object> queryParams) { return getRequest(url, token,HttpMethod.GET, queryParams); } public static <T> String sendPostRequest(String url,String token, Map<String, Object> queryParams,Integer type) { return postRequest(url, token,queryParams,type); } public static <T> String getRequest(String url,String token, HttpMethod method, Map<String, Object> queryParams) { HttpHeaders headers = new HttpHeaders(); //是否携带token if (StringUtils.isNotEmpty(token)){ headers.add(HttpHeaders.AUTHORIZATION, "Bearer "+token); } if (queryParams != null && !queryParams.isEmpty()) { StringBuilder urlBuilder = new StringBuilder(url); urlBuilder.append("?"); for (Map.Entry<String, Object> entry : queryParams.entrySet()) { urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } url = urlBuilder.toString(); } HttpEntity<String> requestEntity = new HttpEntity<>(headers); ResponseEntity<String> responseEntity = httpUtils.restTemplate.exchange(url, method, requestEntity,String.class); return responseEntity.getBody(); } /** * @description type 1 contentType:application/x-www-form-urlencoded 2contentType:application/json(使用了@RequestBody接收参数) */ public static <T> String postRequest(String url,String token,Map<String, Object> queryParams,Integer type) { String result = ""; HttpHeaders headers = new HttpHeaders(); //是否携带token if (StringUtils.isNotEmpty(token)){ headers.add(HttpHeaders.AUTHORIZATION, "Bearer "+token); } //post 请求2种方式 if (Objects.equals(type,1)){ headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); for (String key : queryParams.keySet()) { map.add(key,queryParams.get(key)); } HttpEntity<MultiValueMap<String,Object>> formEntity = new HttpEntity<>(map, headers); result = httpUtils.restTemplate.postForObject(url, formEntity, String.class); } if (Objects.equals(type,2)){ headers.setContentType(MediaType.APPLICATION_JSON); String params = JSON.toJSONString(queryParams); HttpEntity<String> formEntity = new HttpEntity<>(params, headers); result = httpUtils.restTemplate.postForObject(url, formEntity, String.class); } return result; } /** * 发送包含文件的表单数据的POST请求 * * @param data 表单数据,JSON格式的字符串 * @param url 目标URL * @param file 要上传的文件 */ public static String formDataSendPost(String data, String url,String fileKey,File file) { OkHttpClient okHttpClient = new OkHttpClient(); String responseBody = null; try { // 创建Multipart请求体 MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder() .setType(MultipartBody.FORM); // 添加文本参数 com.alibaba.fastjson2.JSONObject jsonObject = JSONObject.parseObject(data); for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { requestBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue().toString()); } // 添加文件参数 if (file != null) { String fileName = file.getName(); RequestBody fileBody = RequestBody.create(okhttp3.MediaType.parse("application/octet-stream"), file); requestBodyBuilder.addFormDataPart(fileKey, fileName, fileBody); } RequestBody requestBody = requestBodyBuilder.build(); // 创建请求 Request request = new Request.Builder() .url(url) .post(requestBody) .build(); // 发送请求并获取响应 Response response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { responseBody = response.body().string(); log.info("数据发送成功:" + responseBody); } else { responseBody = "数据发送失败:" + response.code() + " " + response.message(); log.error("数据发送失败:" + response.code() + " " + response.message()); } } catch (IOException e) { e.printStackTrace(); } return responseBody; } }