spring boot RestTemplate

时间:2022-05-26
本文章向大家介绍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

原文地址:https://www.cnblogs.com/zjf6666/p/16315149.html