android - 如何在 POST 请求中正确传递正文
问题描述
我过去常常在颤振中HTTPClient
发出POST
请求以发布Form
数据,我在表单中有很多字段要发布,但现在我只给出了firstname
,参数以及lastname
请求中的 。但现在我想传递整个as 身体,以便我可以获得所有.email
body
JSON
FormFields
我怎样才能正确地做到这一点?
我的表格包含TextFormFields
,DateTimeFormField
和DropdownButtonFormField
.
API_Manager 类:
Future<AddContactModel> addContact(
String firstName,
String lastName,
String email,
) async {
var client = http.Client();
String addContactUrl =
"https://example.com/ma/api/contacts/new";
String basicAuth = 'Basic examplebasicauthkey';
var response = await client.post(addContactUrl, headers: <String, String>{
'authorization': basicAuth,
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
}, body: {
"firstname": firstName,
"lastname": lastName,
"email": email
});
// print(response.statusCode);
// developer.log(response.body);
if (response.statusCode == 201) {
final String responseString = response.body;
return addContactModelFromJson(responseString);
} else {
return null;
}
}
从代码中可以看出,body
仅包含三个字段。但是我想添加我的所有字段,而不是将所有字段明确地提供给正文,尽管我可以json
直接传递。我是新手,所以我不知道它是否有效?我也会分享我的示例 JSON 数据。
JSON 样本数据:
{
"contact": {
"isPublished": true,
"id": 193208,
"fields": {
"core": {
"firstname": {
"id": "2",
"label": "First Name",
"type": "text",
"value": "Richa"
},
"lastname": {
"id": "3",
"label": "Last Name",
"type": "text",
"value": "Kumari"
},
"email": {
"id": "6",
"label": "Email",
"value": "richa@abc.com"
},
},
"all": {
"id": 193208,
"firstname": "Richa",
"lastname": "Kumari",
"email": "richa@abc.com",
}
},
"...": {
"..." : "..."
}
用户界面代码:
Future saveContact() async {
final String firstName = _firstName.text;
final String lastName = _lastName.text;
final String email = _email.text;
final AddContactModel contact =
await API_Manager().addContact(firstName, lastName, email);
setState(() {
_contact = contact;
});
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Scaffold(
appBar: AppBar(
title: Text('Add Contact'),
actions: <Widget>[
FlatButton(
textColor: Colors.white,
onPressed: () async {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState.validate()) {
await saveContact();
}
},
child: Text(
'SAVE',
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
shape:
CircleBorder(side: BorderSide(color: Colors.transparent)),
)
],
),
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.all(5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_contact == null
? Container()
:
//Text("The user ${_contact.contact.fields.all.firstname} is created successfully at time ${_contact.contact.lastActive.toIso8601String()}"),
TextFormField(
onSaved: null,
controller: _ipCountryCode,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'IP Country Code',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DateTimeFormField(
decoration: InputDecoration(
labelText: 'Time First Seen',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
onDateSelected: (DateTime value) {
setState(() {
timeFirstSeen = value;
});
},
),
),
],
),
TextFormField(
onSaved: null,
controller: _eventRevenue,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Event Revenue',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
TextFormField(
onSaved: null,
controller: _sendsSinceLastEngagement,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Sends since last engagement',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
TextFormField(
onSaved: null,
controller: _marketingEmailsOpened,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Marketing Emails Opened',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DateTimeFormField(
decoration: InputDecoration(
labelText: 'Last marketing email click date',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
onDateSelected: (DateTime value) {
setState(() {
lastMarketingEmailClickDate = value;
});
},
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DropdownButtonFormField(
isExpanded: true,
decoration: InputDecoration(
labelText: 'Email Address Quarantined',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
value: emailAddressQuarantined,
onChanged: (newValue) {
setState(() {
emailAddressQuarantined = newValue;
});
},
items: emailAddressQuarantinedItem.map((valueItem) {
return DropdownMenuItem(
value: valueItem,
child: Text(valueItem),
);
}).toList(),
),
),
],
),
TextFormField(
onSaved: null,
controller: _socialAwarenessClicks,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Social Awareness Clicks',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DropdownButtonFormField(
decoration: InputDecoration(
labelText: 'Lead Status',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
value: leadStatus,
onChanged: (newValue) {
setState(() {
leadStatus = newValue;
});
},
items: leadStatusItem.map((valueItem) {
return DropdownMenuItem(
value: valueItem,
child: Text(valueItem),
);
}).toList(),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DateTimeFormField(
decoration: InputDecoration(
labelText: 'Create date',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
onDateSelected: (DateTime value) {
setState(() {
createDate = value;
});
},
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DateTimeFormField(
decoration: InputDecoration(
labelText: 'Became an evangelist date',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
onDateSelected: (DateTime value) {
setState(() {
becameAnEvangelistDate = value;
});
},
),
),
],
),
TextFormField(
onSaved: null,
controller: _firstName,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'First Name',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
TextFormField(
onSaved: null,
controller: _lastName,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Last Name',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
TextFormField(
//validator: validateEmail,
onSaved: null,
controller: _email,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Email',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
TextFormField(
onSaved: null,
controller: _reasonForEmailUnsubscribe,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Reason for email unsubscribe',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DropdownButtonFormField(
isExpanded: true,
decoration: InputDecoration(
labelText: 'Tags',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
value: tags,
onChanged: (newValue) {
setState(() {
tags = newValue;
});
},
items: tagsItem.map((valueItem) {
return DropdownMenuItem(
value: valueItem,
child: Text(valueItem),
);
}).toList(),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DropdownButtonFormField(
isExpanded: true,
decoration: InputDecoration(
labelText: 'Select a company',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
value: selectCompany,
onChanged: (newValue) {
setState(() {
selectCompany = newValue;
});
},
items: selectCompanyItem.map((valueItem) {
return DropdownMenuItem(
value: valueItem,
child: Text(valueItem),
);
}).toList(),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DropdownButtonFormField(
isExpanded: true,
decoration: InputDecoration(
labelText: 'Contact Owner',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
value: contactOwner,
onChanged: (newValue) {
setState(() {
contactOwner = newValue;
});
},
items: contactOwnerItem.map((valueItem) {
return DropdownMenuItem(
value: valueItem,
child: Text(valueItem),
);
}).toList(),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: DropdownButtonFormField(
decoration: InputDecoration(
labelText: 'Stage',
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(8)),
value: stage,
onChanged: (newValue) {
setState(() {
stage = newValue;
});
},
items: stageItem.map((valueItem) {
return DropdownMenuItem(
value: valueItem,
child: Text(valueItem),
);
}).toList(),
),
),
],
),
],
),
),
),
));
}
正如您在方法中可以看到的,和saveContact()
的值和 被成功发布,因为它在 API 调用的主体中,但是当主体将包含整个 JSON 数据时,该代码将如何变化?我应该如何访问所有其他字段值?firstName
lastName
email
解决方案
推荐阅读
- ios - 每次按下按钮时,如何从标签“26”中减去 1?(斯威夫特初学者)
- pandas - Pandas 折线图 - Y 轴将小数值转换为浮点数
- c# - HackerRank 攀登排行榜
- python - 文本输入的实时自动完成如何在 Python 中工作?
- java - MPAndroidChart 如何更改超过限制线的条形图颜色?
- powershell - 找不到与参数名称“文件”匹配的参数
- python - 将 json 文件与 oracle 表数据进行比较的实用程序
- airflow - 如何在 Airflow 发起追赶?
- beautifulsoup - 使用 BeautifulSoup 提取
- 元素并包含存储它的结构
- angular - 具有服务器端分页“滚动”的角度材料数据表