【问题标题】:what is the best way of doing a http post in dart?在 dart 中发布 http 帖子的最佳方式是什么?
【发布时间】:2020-02-07 17:59:03
【问题描述】:

尝试发布此: {grant_type: 密码, 密码: 123456, 用户名: 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();
}

但响应显示 {"error":"invalid_request","error_description":"缺少必需的 'grant_type' 参数。"}

在邮递员身上尝试得到不同的结果

screen shot of response with postman

【问题讨论】:

  • 您确定响应来自请求,而不是来自颤振本身吗?

标签: flutter dart http-post


【解决方案1】:

我认为没有最好的方法。目前我使用的是 Retrofit For Dart,这很方便,因为它会生成实际的实现。

例如,

@POST('/oauth/token')
@Headers(Constant.HEADER)
Future<LoginResponse> loginByEmail(@Query("email") String email, 
@Query("password") String password, @Query("grant_type") String grantType);

会变成

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

【讨论】:

  • 最终使用了这种方法。谢谢。
【解决方案2】:

好的,我不知道您使用的方法,但我会向您展示我的有效方法,它应该可以帮助您理解请求的结构。

服务器端代码显示:

POST - /api/getInfo

Request:

{
user_phone: ''
notes: ''
}

Response:

{
status: ''
}

所以这是服务器端代码,这个请求(一个发布请求)需要一个变量 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
}

现在有比这更多的方法,但是,这应该可以帮助您找出原始代码可能存在的问题,或者需要如何修改它才能完成您想要做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多