Flutter 在dart中执行http post的最佳方法是什么?

Flutter 在dart中执行http post的最佳方法是什么?,flutter,dart,http-post,Flutter,Dart,Http Post,尝试发布以下内容: {grant_type:password,password:123456,username:user1234}使用以下代码 Future<HttpClientResponse> apiRequest(String url, String username, String password) async { Map jsonMap = {'grant_type':'password','password':password,'username':username};

尝试发布以下内容: {grant_type:password,password:123456,username:user1234}使用以下代码

Future<HttpClientResponse> apiRequest(String url, String username, String password) async {
Map jsonMap = {'grant_type':'password','password':password,'username':username};
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.add(utf8.encode((jsonMap.toString())));
print((jsonMap.toString()));
return await request.close();
}
未来APIRest(字符串url、字符串用户名、字符串密码)异步{
Map jsonMap={'grant_type':'password','password':password,'username':username};
HttpClient HttpClient=新HttpClient();
HttpClientRequest=wait-httpClient.postrl(Uri.parse(url));
request.headers.set(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=UTF-8”);
add(utf8.encode((jsonMap.toString()));
打印((jsonMap.toString());
返回等待请求。关闭();
}
但响应为{“error”:“无效的请求”,“error\u描述”:“缺少必需的'grant\u type'参数”。}

在邮递员身上试试,结果不一样


我认为没有最好的办法。目前我使用的是Dart改造,这非常方便,因为它生成了实际的实现

比如说,

@POST('/oauth/token')
@Headers(Constant.HEADER)
Future<LoginResponse> loginByEmail(@Query("email") String email, 
@Query("password") String password, @Query("grant_type") String grantType);
@POST('/oauth/token')
@标题(常量.标题)
未来登录邮件(@Query(“email”)字符串电子邮件,
@查询(“密码”)字符串密码、@Query(“授权类型”)字符串授权类型);
将成为

@override
loginByEmail(email, password, grantType) async {
  ArgumentError.checkNotNull(email, 'email');
  ArgumentError.checkNotNull(password, 'password');
  ArgumentError.checkNotNull(grantType, 'grantType');
  const _extra = <String, dynamic>{};
  final queryParameters = <String, dynamic>{
    'email': email,
    'password': password,
    'grant_type': grantType
  };
  final _data = <String, dynamic>{};
  final Response<Map<String, dynamic>> _result = await _dio.request(
    '/oauth/token',
    queryParameters: queryParameters,
    options: RequestOptions(
        method: 'POST',
        headers: <String, dynamic>{

        },
        extra: _extra,
        baseUrl: baseUrl),
    data: _data);
  final value = LoginResponse.fromJson(_result.data);
  return Future.value(value);
}
@覆盖
登录邮件(电子邮件、密码、grantType)异步{
ArgumentError.checkNotNull(电子邮件,'email');
ArgumentError.checkNotNull(密码,'password');
ArgumentError.checkNotNull(grantType,'grantType');
const_extra={};
最终查询参数={
“电子邮件”:电子邮件,
“密码”:密码,
“授予类型”:授予类型
};
最终_数据={};
最终响应结果=等待请求(
“/oauth/token”,
查询参数:查询参数,
选项:请求选项(
方法:“POST”,
标题:{
},
额外的:_额外的,
baseUrl:baseUrl),
数据:_数据);
最终值=LoginResponse.fromJson(_result.data);
返回未来值(value);
}

好的,我不知道您使用的方法,但我将向您展示我的有效方法,它将帮助您理解请求的结构

服务器端代码显示:

POST - /api/getInfo

Request:

{
user_phone: ''
notes: ''
}

Response:

{
status: ''
}
这是服务器端代码,这个请求(post请求)需要一个可变的user_phone和一个可变的notes。它给了我们地位的回应

因此,我要做的是向该服务器发出单个请求,如下所示:

String basicAuth = 'Basic ' + base64Encode(utf8.encode('$username:$password')); // <--- Generate the Basic Auth string
http.Response response = await http.get(
  'https://myRandomServer.com/api/getInfo',
  headers: <String, String>{'authorization': basicAuth}, // <--- Authorization in header
  body: {'user_phone': '5555555555', 'notes': 'Some note'}, // <--- Data required in body of request
);

if (response.body != null) {
  Map data = jsonDecode(responseStatus.body); // <--- Decoding from json file response
  myStatus = data.['status']; // <----  Piece of information I need
}

String basicAuth='Basic'+base64Encode(utf8.encode('$username:$password'));//您确定响应来自请求,而不是颤振本身吗?最终使用了该方法。谢谢