Flutter carries JSON parameter post request

To send network requests with JSON parameters in Flutter, you can use HTTP libraries such as httpor dio. Here is an example of using httpthe library to send a network request with JSON parameters:

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

// 创建参数Map
Map<String, dynamic> params = {
  'name': 'John',
  'age': 25,
};

// 将Map对象转换为JSON字符串
String jsonParams = jsonEncode(params);

// 设置请求头
Map<String, String> headers = {
  'Content-Type': 'application/json',
};

// 发送POST请求
http.Response response = await http.post(
  Uri.parse('http://example.com/api/endpoint'),
  headers: headers,
  body: jsonParams,
);

// 解析响应
if (response.statusCode == 200) {
  // 请求成功
  Map<String, dynamic> responseData = jsonDecode(response.body);
  // 处理响应数据
} else {
  // 请求失败
  print('请求失败:${response.statusCode}');
}

In the above example, a Map of parameters is first created and converted to a JSON string. Then set the request header to indicate that the request type is JSON. Finally, use http.post()the method to send a POST request, and pass the URL, request header and request body (ie JSON parameters). After waiting for the request to complete, check the response status code to determine whether the request is successful, and parse the response JSON data.

Please note that the URL and request headers in the example need to be modified according to the actual situation. In addition, you can also use other HTTP libraries (such as dio) to send network requests, and you need to pay attention to the usage and related configuration of the library when using it.

Guess you like

Origin blog.csdn.net/DongShanYuXiao/article/details/132031108