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