RestTemplate post 方式 发起 post 请求

来自姬鸿昌的知识库
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1AN411Z7mx?p=11

Application Service 中的 DemoController.java

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class DemoController {

    @RequestMapping("/demo4")
    public String demo4(String name, Integer age, @RequestBody Map<String, Object> map) {
        System.out.println(map);
        return "name:" + name + ",age:" + age;
    }

}
{name=jihch, age=15}



Application Client 中的 单元测试

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class ClientApplicationTests {

    @Test
    void postForObject() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "jihch");
        map.put("age", 15);
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject("http://localhost:8080/demo4?name=jihch&age=15", map, String.class);
        System.out.println(result);
    }

}
name:jihch,age:15