SpringCloud 消费方请求对象到提供服务方出现org.springframework.web.client.HttpClientErrorException: 415 null的解决

    科技2025-11-07  12

    背景: 实现一个列表保存的需求,消费者前端页面将修改后的数据以JSON格式上传到消费者后端封装为实体类,消费者后端再通过restTemplate对象将这个实体类请求到服务者进行保存。 然而出现错误 org.springframework.web.client.HttpClientErrorException: 415 null 原因: 后来百度了下,原因是消费方没有设置Media类型,我们要知道的是,restTemplate组件是基于http协议来实现请求的,而请求中必定是要带有一些协议头的;因此一般情况下我们不需要特别声明协议头,但在传输json数据时,则需要声明协议头。 解决: 在消费方设置Media类型和协议头。 消费方代码内容如下:

    /** * 保存修改信息 * @param matchsInfoObj * @return */ @PostMapping("/matchSave") public String matchSave(MatchsInfo matchsInfoObj) { //创建HttpHeaders对象。 HttpHeaders httpHeadersObj = new HttpHeaders(); //设置内容类型 httpHeadersObj.setContentType(MediaType.APPLICATION_JSON); //创建HttpEntity对象 HttpEntity<MatchsInfo> param = new HttpEntity<MatchsInfo>(matchsInfoObj,httpHeadersObj); //发送请求 restTemplateObj.put("http://PROVIDER-PARAM/matchSave",param); return "matchofokhttp#matchInfoData"; }

    提供方代码内容如下:

    /** * 保存修改信息 * @param matchsInfoObj */ @PutMapping("/matchSave") public void matchSave(@RequestBody MatchsInfo matchsInfoObj) { System.out.println("提供方:"+matchsInfoObj); }

    参考:https://blog.csdn.net/qq_16257945/article/details/104794593 参考:https://ask.csdn.net/questions/775401

    Processed: 0.012, SQL: 8