返回

Java中restTemplate的使用

发布时间:2023-12-01 23:56:36 219

原文链接

代码地址

本文介绍restTemplate基础用法。

Java中get和post的用法请参考:https://mp.weixin.qq.com/s/mC0D1nuCqIori5bWtLorWQ

1 提供get/post接口

1.1 Controller

@RestController
@RequestMapping("/homepage")
public class MyController {

    @Autowired
    MyService myService;

    // 提供get接口
    @GetMapping("/provideGet")
    public Map provideGet(){
        return myService.provideGet();
    }

    // 提供post接口
    @PostMapping("/providePost")
    public Map providePost(@RequestParam("number") int number, @RequestParam("name") String name) {
        return myService.providePost(number, name);
    }

    // 提供map参数的post接口
    @PostMapping("/providePostByMap")
    public Map providePostByMap(@RequestParam Map map) {
        return myService.providePostByMap(map);
    }

    // 调用get接口
    @GetMapping("/useGet")
    public Map useGet() {
        return myService.useGet();
    }
}

1.2 Service

@Service
@EnableScheduling
public class MyService {

    public Map provideGet() {
        Map res = new HashMap<>();
        res.put("number", "3");
        res.put("name", "张三get");
        System.out.println("provideGet res:" + res + "\n");
        return res;
    }

    public Map providePost(int number, String name) {
        Map res = new HashMap<>();
        res.put("number", number);
        res.put("name", name);

        return res;
    }

    public Map providePostByMap(Map map) {
        int number = map.get("number") == null ? 0 : Integer.parseInt((String) map.get("number"));
        String name = map.get("name") == null ? "" : (String) map.get("name");
        Map res = new HashMap<>();
        res.put("number", number);
        res.put("name", name);

        System.out.println("providePostByMap res:" + res + "\n");
        return res;
    }
}

2 调用get/post接口

使用restTemplate调用get/post接口。

  • getForObject():返回值是HTTP协议的响应体
  • getForEntity():返回的是ResponseEntityResponseEntity是对HTTP响应的封装,除了包含响应体,还包含HTTP状态码、contentType、contentLength、Header等信息

2.1 Controller

@RestController
@RequestMapping("/homepage")
public class MyController {    
	@Autowired
    MyService myService;

    // 调用get接口
    @GetMapping("/useGet")
    public Map useGet() {
        return myService.useGet();
    }

    // 调用get接口验证账号密码
    @GetMapping("/useGetByPsw")
    public Map useGetByPsw() {
        return myService.useGetByPsw();
    }

    // 调用post接口
    @PostMapping("/usePost")
    public Map usePost() {
        return myService.usePost();
    }
}

2.2 Service

@Service
@EnableScheduling
public class MyService {
    @Resource
    private RestTemplate restTemplate;

    String getURL = "http://localhost:8081/homepage/provideGet";
    String postURL = "http://localhost:8081/homepage/providePostByMap";

    public Map useGet() {
        // getForObject返回值是HTTP协议的响应体
        String strObject = restTemplate.getForObject(getURL, String.class);
        JSONObject jsonObject = JSONObject.parseObject(strObject);

        // getForEntity返回的是ResponseEntity,是对HTTP响应的封装
        ResponseEntity responseData = restTemplate.getForEntity(getURL, ResponseResult.class);
        Map returnData = new HashMap<>();
        returnData.put("StatusCode:", responseData.getStatusCode());
        returnData.put("Body:", responseData.getBody());

        System.out.println("useGet jsonObject:" + jsonObject + "\n");
        System.out.println("useGet responseData:" + responseData + "\n");
        System.out.println("useGet returnData:" + returnData + "\n");
        return returnData;
    }

    public Map useGetByPsw() {

        RestTemplateBuilder builder = new RestTemplateBuilder();
        RestTemplate restTemplate = builder.basicAuthentication("username", "password").build();

        // getForEntity返回的是ResponseEntity,是对HTTP响应的封装
        ResponseEntity responseData = restTemplate.getForEntity(getURL, ResponseResult.class);
        Map returnData = new HashMap<>();
        returnData.put("StatusCode:", responseData.getStatusCode());
        returnData.put("Body:", responseData.getBody());

        System.out.println("useGetByPsw returnData:" + responseData + "\n");
        System.out.println("useGetByPsw returnData:" + returnData + "\n");
        return returnData;
    }

    public Map usePost() {
        //RestTemplate在postForObject时,用MultiValueMap,不可使用HashMap。
        MultiValueMap sendData = new LinkedMultiValueMap<>();
        sendData.add("number", "3");
        sendData.add("name", "张三post");

        // getForObject返回值是HTTP协议的响应体
        String strObject = restTemplate.postForObject(postURL, sendData, String.class);
        JSONObject jsonObject = JSONObject.parseObject(strObject);

        // getForEntity返回的是ResponseEntity,是对HTTP响应的封装
        ResponseEntity responseData = restTemplate.postForEntity(postURL, sendData, ResponseResult.class);
        Map returnData = new HashMap<>();
        returnData.put("StatusCode:", responseData.getStatusCode());
        returnData.put("Body:", responseData.getBody());

        System.out.println("usePost jsonObject:" + jsonObject + "\n");
        System.out.println("usePost responseData:" + responseData + "\n");
        System.out.println("usePost returnData:" + returnData + "\n");
        return returnData;
    }
}

   

学习更多编程知识,请关注我的公众号:

代码的路

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
java 类变量初始化顺序 2023-12-01 21:02:20