如何在flutter中使用表单数据进行http发布?

编程入门 行业动态 更新时间:2024-10-24 12:29:22
本文介绍了如何在flutter中使用表单数据进行http发布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试发出http发布请求,并且我需要将正文指定为 form-data ,因为服务器不会将请求作为原始请求。

I'm trying to do a http post request and I need to specify the body as form-data, because the server don't take the request as raw.

这就是我在做什么:

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 = 'na57.salesforce/services/oauth2/token'; var requestBody = { 'grant_type':'password', 'client_id':'3MVG9dZJodJWITSviqdj3EnW.LrZ81MbuGBqgIxxxdD6u7Mru2NOEs8bHFoFyNw_nVKPhlF2EzDbNYI0rphQL', 'client_secret':'42E131F37E4E05313646E1ED1D3788D76192EBECA7486D15BDDB8408B9726B42', 'username':'example@mail.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": "na57.salesforce", "id": "login.salesforce/id/00D0b000000Bb08EAC/0050b000005nstiAAA", "token_type": "Bearer", "issued_at": "1567993324968", "signature": "1+Zd/dSh9i7Moh2U0nFJLdXkVHqPlPVU6emwdYzXDPk=" }

您可以在以下位置进行测试邮递员在原始(您获得实际响应)和表单数据(您获得预期响应)之间切换正文

You can test this on postman switching the body between raw (you get the actual response) and form-data (you get the expected response)

PS:标头是由客户端工具创建的临时标头。

PS: The headers are temporary headers created by the client tool.

推荐答案

请改用Map,因为正文位于http包中仅具有3种类型:字符串,列表或映射。试试这个:

Use Map instead, because body in http package only has 3 types: String, List or Map. Try this:

final uri = 'na57.salesforce/services/oauth2/token'; var map = new Map<String, dynamic>(); map['grant_type'] = 'password'; map['client_id'] = '3MVG9dZJodJWITSviqdj3EnW.LrZ81MbuGBqgIxxxdD6u7Mru2NOEs8bHFoFyNw_nVKPhlF2EzDbNYI0rphQL'; map['client_secret'] = '42E131F37E4E05313646E1ED1D3788D76192EBECA7486D15BDDB8408B9726B42'; map['username'] = 'example@mail.us'; map['password'] = 'ABC1234563Af88jesKxPLVirJRW8wXvj3D'; http.Response response = await http.post( uri, body: map, );

更多推荐

如何在flutter中使用表单数据进行http发布?

本文发布于:2023-11-24 18:50:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   数据   如何在   http   flutter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!