RestTemplate请求
package com.istrong.guarantee.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.client.RestTemplate; /** * @program: sm_guarantee_platform * @ClassName AppConfig * @description:注册bean、系统配置注解开启 * @author: 黄涛 * @create: 2025-01-10 16:03 * @Version 1.0 **/ @Configuration public class AppConfig { /** * 注册restTemplate的bean * @return */ @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
package com.istrong.guarantee.component; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.springframework.http.*; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.util.Map; import java.util.stream.Collectors; /** * @program: sm_guarantee_platform * @ClassName ThirdPartyService * @description:HTTP访问的模板类 * @author: 黄涛 * @create: 2025-01-10 15:41 * @Version 1.0 **/ @Component public final class RestTemplateService { private final RestTemplate restTemplate; public RestTemplateService(RestTemplate restTemplate){ this.restTemplate = restTemplate; } /** * post,application/json * @param url * @param param * @return */ public final Map post(String url, Map<String, Object> param) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Map<String, Object>> entity = new HttpEntity<>(param, headers); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); return JSONObject.parseObject(response.getBody()); } /** * get,application/x-www-form-urlencoded * @param url * @return */ public final Map get(String url) { ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); return JSONObject.parseObject(response.getBody()); } /** * get,application/x-www-form-urlencoded * @param url * @param map * @return */ public final Map get(String url,Map<String,String> map) { url += "?" + map.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&")); ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); Map ret_map = JSON.parseObject(responseEntity.getBody()); return ret_map; } }
吾乃代码搬运工,侵联删
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了