Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 使用http包对颤振执行POST请求_Flutter_Dart_Dart Http - Fatal编程技术网

Flutter 使用http包对颤振执行POST请求

Flutter 使用http包对颤振执行POST请求,flutter,dart,dart-http,Flutter,Dart,Dart Http,我正在尝试使用颤振来达到这个终点 我让它在邮递员和卷发上工作 curl version: curl https://api.particle.io/oauth/token \ -u particle:particle \ -d grant_type=password \ -d "my.email@gmail.com" \ -d "my_password" 邮递员: 在curl和postman上,我都得到了带有访问令牌的响应 但

我正在尝试使用颤振来达到这个终点

我让它在邮递员和卷发上工作

curl version: 
    curl https://api.particle.io/oauth/token \
       -u particle:particle \
       -d grant_type=password \
       -d "my.email@gmail.com" \
       -d "my_password"
邮递员:

在curl和postman上,我都得到了带有访问令牌的响应

但是当我试图在Flutter上实现这个时,我得到了一个错误响应。 这是我关于颤振的代码

Future<Response> getPublicKey() async {
LoginRequestModel requestModelBody = LoginRequestModel(grantType: "password",
    username: "my.email@gmail.com", password: "my_password");
Map<String, dynamic> requestBody = requestModelBody.toJson();
String bodyString = json.encode(requestBody);
//    String formBody = Uri.encodeQueryComponent(bodyString);
print("Body string: "+bodyString);
String url = "https://api.particle.io/oauth/token";
String credentials = "particle:particle";

Map<String, String> headers = {
  HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
  HttpHeaders.authorizationHeader: "Authorization $credentials",
};

return await post(url, headers: headers, body: bodyString);
这就是我得到的错误:

{"error":"invalid_request","error_description":"Invalid or missing grant_type parameter"}
我猜我做的表单编码是错误的,但我不能找出正确的方法来形成encod的身体

问题:如何使用flifter访问REST端点

curl
命令转换为省道代码有一个很好的方法

粘贴curl命令将提供:

import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  var uname = 'particle';
  var pword = 'particle';
  var authn = 'Basic ' + base64Encode(utf8.encode('$uname:$pword'));

  var data = {
    'grant_type': 'password',
    'my.email@gmail.com': '',
    'my_password': '',
  };

  var res = await http.post('https://api.particle.io/oauth/token', headers: {'Authorization': authn}, body: data);
  if (res.statusCode != 200) throw Exception('post error: statusCode= ${res.statusCode}');
  print(res.body);
}
与您的Postman屏幕截图相比,似乎表明您的curl命令实际上并不正确,因此我将其更改为:

  var data = {
    'grant_type': 'password',
    'username': 'my.email@gmail.com',
    'password': 'my_password',
  };
  var data = {
    'grant_type': 'password',
    'username': 'my.email@gmail.com',
    'password': 'my_password',
  };