Java RestTemplate post 请求报错

用postMan是可以正常登录返回token的,但是用 RestTemplate发送请求后报错

img

img

img

你使用 PostMan 调用接口时请求内容类型是 application/json,使用代码调用接口时请求内容类型是 application/x-www-form-urlencoded,这个接口不识别 form 内容类型,因此报错,改成 json 内容类型再试试,RestTemplate json 内容类型示例代码如下,你可以参考来改下。

    public void test() {
        User user = new User().setUsername("hkp").setPassword("123");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<User> httpEntity = new HttpEntity<>(user, headers);
        RestTemplate restTemplate = new RestTemplate();
        User response = restTemplate.postForObject("http://127.0.0.1:8080/register", httpEntity, User.class);
        System.out.println(response);
    }

这个示例也是从我文章里面摘抄的,更多 RestTemplate 内容,可以参考 Spring HTTP 客户端神器 RestTemplate 详解_zzuhkp的博客-CSDN博客
如有帮助,请采纳。

400,要么是请求路径没写对,要么是参数没写对。