SpringBoot 接口报错:Content type ‘text/plain;charset=UTF-8‘ not supported

本文介绍了一种常见的HTTP状态码415错误的解决方案。该错误通常发生在客户端尝试向服务器发送不支持的内容类型时。文章详细说明了如何通过更改Postman中的请求内容类型来修复此问题。

控制台显示

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported]

接口
在这里插入图片描述
使用postman测试,请求参数如下,接口返回415
在这里插入图片描述
解决:
使用postman时发送json时,默认是text,记得修改为json。
使用text时的颜色都是黑的,用json时postman会调整下颜色。
在这里插入图片描述
在这里插入图片描述
修改后
在这里插入图片描述

接口报 `Content type 'text/plain;charset=utf-8' not supported` 错误时,通常是因为服务器端无法处理 `text/plain` 这种内容类型的请求。以下是一些可能的解决方法: ### 客户端层面 - **修改请求的 Content-Type**:确保客户端发送请求时指定的 `Content-Type` 是服务器端支持的类型。例如,如果服务器端支持 `application/json`,可以将请求的 `Content-Type` 设置为 `application/json`。 ```python import requests import json data = {'key': 'value'} headers = {'Content-Type': 'application/json'} response = requests.post('http://example.com/api', data=json.dumps(data), headers=headers) ``` - **检查请求库的默认设置**:某些请求库可能有默认的 `Content-Type` 设置,需要检查并修改。例如,在使用 `fetch` API 时: ```javascript const data = { key: 'value' }; fetch('http://example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ### 服务器端层面 - **配置服务器支持 text/plain**:如果服务器端需要支持 `text/plain` 类型的请求,可以在配置文件中添加相应的支持。以 Spring Boot 为例,可以通过配置消息转换器来支持 `text/plain`: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.nio.charset.StandardCharsets; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public StringHttpMessageConverter stringHttpMessageConverter() { StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8); converter.setSupportedMediaTypes(java.util.List.of(org.springframework.http.MediaType.TEXT_PLAIN)); return converter; } } ``` - **修改接口方法的注解**:确保接口方法的注解可以处理 `text/plain` 类型的请求。例如,在 Spring Boot 中: ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @PostMapping(value = "/api", consumes = "text/plain") public String handleTextRequest(@RequestBody String requestBody) { return "Received: " + requestBody; } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值