【发布时间】:2020-01-10 18:15:04
【问题描述】:
我正在尝试执行 http post 请求,我需要将正文指定为 form-data,因为服务器不会将请求视为原始请求。
这就是我正在做的:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
postTest() async {
final uri = 'https://na57.salesforce.com/services/oauth2/token';
var requestBody = {
'grant_type':'password',
'client_id':'3MVG9dZJodJWITSviqdj3EnW.LrZ81MbuGBqgIxxxdD6u7Mru2NOEs8bHFoFyNw_nVKPhlF2EzDbNYI0rphQL',
'client_secret':'42E131F37E4E05313646E1ED1D3788D76192EBECA7486D15BDDB8408B9726B42',
'username':'example@mail.com.us',
'password':'ABC1234563Af88jesKxPLVirJRW8wXvj3D'
};
http.Response response = await http.post(
uri,
body: json.encode(requestBody),
);
print(response.body);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Container(
child: Center(
child: RaisedButton(
child: Text('Press Here'),
onPressed: (){
postTest();
},
),
),
),
);
}
}
这是实际的响应:
{
"error": "unsupported_grant_type",
"error_description": "grant type not supported"
}
这是预期的响应:
{
"access_token": "00D0b000000Bb08!AR8AQO.s8mAGXCbwV77FXNLQqc2vtl8g6_16miVbgWlQMsuNHsaf2IGLUwnMVXBOfAj19iznhqhwlPOi4tagvf7FFgiJJgoi",
"instance_url": "https://na57.salesforce.com",
"id": "https://login.salesforce.com/id/00D0b000000Bb08EAC/0050b000005nstiAAA",
"token_type": "Bearer",
"issued_at": "1567993324968",
"signature": "1+Zd/dSh9i7Moh2U0nFJLdXkVHqPlPVU6emwdYzXDPk="
}
您可以在 postman 在 raw(得到实际响应)和 form-data(得到预期响应)之间切换正文进行测试
PS:标头是客户端工具创建的临时标头。
【问题讨论】:
-
你找到相同的解决方案了吗?请分享
-
有什么解决办法吗?来自@MalithKuruwita 的上述链接也没有被接受的答案
-
@EightRice 如果您想将数据发送到接受内容类型的服务器:x-www-form-urlencoded,我提供的上述 URL 有效。它适用于文本数据。但是如果你想发送多部分/表单数据。像文件或图像到服务器(二进制数据),使用它(developerlibs.com/2020/07/…)。该博客还展示了如何发送文本数据。根据服务器接受的内容类型使用相关的
标签: http flutter dart form-data