處理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]。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM