處理flutter http請求添加application/json報錯Cannot set the body fields of a Request with content-type 「appli

在flutter中在http請求發送時設置"content-type": "application/json"會出現報錯Cannot set the body fields of a Request with content-type 「application/json」javascript

請求以下:java

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;
});

  

請求發送以後會出現以下報錯json

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處理要提交的參數app

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;
});

  

處理以後再提交便可成功ui

 

注意:

[body]設置請求的正文。它能夠是[String],[List]或[Map]。若是它是一個String,則使用[encoding]進行編碼,並將其用做請求的主體。請求的內容類型將默認爲「text / plain」。編碼

若是[body]是List,它將用做請求正文的字節列表。url

若是[body]是Map,則使用[encoding]將其編碼爲表單字段。請求的內容類型將設置爲"application/x-www-form-urlencoded"這不能被覆蓋。[encoding]默認爲[utf8]。spa

相關文章
相關標籤/搜索