用postMan是可以正常登录返回token的,但是用 RestTemplate发送请求后报错
2条回答 默认 最新
关注
你使用 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博客
如有帮助,请采纳。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报