zoukankan      html  css  js  c++  java
  • 处理flutter http请求添加application/json报错Cannot set the body fields of a Request with content-type “application/json”

    在flutter中在http请求发送时设置"content-type": "application/json"会出现报错Cannot set the body fields of a Request with content-type “application/json”

    请求如下:

    final putResponse = await http.put('http://192.168.201.21/user/modifyUser',
        body: putData,
        headers: {"token": userBasicsInfo.userTokenResult,"content-type": "application/json"}
    ).then((response){
      var backResult;
      if(response.statusCode == 200){
        Utf8Decoder utf8decoder = Utf8Decoder();
        backResult = json.decode(utf8decoder.convert(response.bodyBytes));
      }else{
        print('数据请求错误:${response.statusCode}');
      }
      return backResult;
    });
    

      

    请求发送之后会出现如下报错

    E/flutter ( 7295): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type "application/json".
    

      

    解决方法

    通过jsonEncode处理要提交的参数

    final putData = jsonEncode(params);    // 处理提交参数
    final putResponse = await http.put('http://192.168.201.21/user/modifyUser',
        body: putData,
        headers: {"token": userBasicsInfo.userTokenResult,"content-type": "application/json"}
    ).then((response){
      var backResult;
      if(response.statusCode == 200){
        Utf8Decoder utf8decoder = Utf8Decoder();
        backResult = json.decode(utf8decoder.convert(response.bodyBytes));
      }else{
        print('数据请求错误:${response.statusCode}');
      }
      return backResult;
    });
    

      

    处理之后再提交即可成功

    注意:

    [body]设置请求的正文。它可以是[String],[List]或[Map]。如果它是一个String,则使用[encoding]进行编码,并将其用作请求的主体。请求的内容类型将默认为“text / plain”。

    如果[body]是List,它将用作请求正文的字节列表。

    如果[body]是Map,则使用[encoding]将其编码为表单字段。请求的内容类型将设置为"application/x-www-form-urlencoded"这不能被覆盖。[encoding]默认为[utf8]。

     

  • 相关阅读:
    Dapper ORM 用法—Net下无敌的ORM(转)
    微軟将从 .NET 4 以后的版本弃用 System.Data.OracleClient 以及Oracle 的各种连接方法
    最火的.NET开源项目
    sql日期格式化
    项目失败总结
    C#,往线程里传参数的方法总结
    线程的几种用法
    小程序api-01-abcdefg
    cnpm
    关于mpvue和wafer2-client-sdk的 微信登录失败,请检查网络状态
  • 原文地址:https://www.cnblogs.com/gxsyj/p/11011288.html
Copyright © 2011-2022 走看看