获取text/plain格式http请求中的数据

转载:https://blog.csdn.net/Jin19950615/article/details/85062215

springboot项目,在接收text/plain格式的时候,无法通过@requestBody得到请求中的json信息,需要对请求中的参数进行解析。

@requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。###

异常 type 'text/plain;charset=UTF-8' not supported。

/**
 * 解析text/plain格式请求中的json
 * 
 * @param request
 * @return
 */
public static String fetchPostByTextPlain(HttpServletRequest request) {
   try {
      BufferedReader reader = request.getReader();
      char[] buf = new char[512];
      int len = 0;
      StringBuffer contentBuffer = new StringBuffer();
      while ((len = reader.read(buf)) != -1) {
         contentBuffer.append(buf, 0, len);
      }
      return contentBuffer.toString();
 
   } catch (IOException e) {
      e.printStackTrace();
      log.error("[获取request中用POST方式“Content-type”是“text/plain”发送的json数据]异常:{}", e.getCause());
   }
   return "";
}
原文地址:https://www.cnblogs.com/wanthune/p/11101179.html