spring boot RestTemplate
服务端代码
接口
package com.example.templtedemo.testTemplte; import org.springframework.stereotype.Service; @Service public class UserService { public String getUser(String name){ return name; } }
controller
package com.example.templtedemo.testTemplte; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RequestMapping("/test") @RestController public class TemplteController { @Autowired private UserService service; @RequestMapping("/getUser") public String getUserTest(String name) { return service.getUser(name); } }
客户端
controller
package com.example.democonsumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; @RequestMapping("Jtml") @RestController public class Consumer { @RequestMapping("jjc") public String getUser() { String url = null; String s = null; try { RestTemplate template = new RestTemplate(); url = "http://127.0.0.1:8080/test/getUser?name=aa"; URI uri = URI.create(url); s = template.getForObject(uri, String.class); System.out.println(s); } catch (Exception e) { e.printStackTrace(); } return s; } }
运行两个项目访问 地址 http://localhost:8081/Jtml/jjc
注意 两个项目端口要不一样,不然启动报错
url要加上http 不要用 localhost
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
2018-05-26 Warning: Cannot read drop down range Unrecognized token 60