dart:io中具有json内容类型的Http POST请求 [英] Http POST request with json content-type in dart:io

查看:405
本文介绍了dart:io中具有json内容类型的Http POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用控制台dart应用程序执行HTTP POST(使用 dart:io 或可能是 package:http

How to perform HTTP POST using the console dart application (using dart:io or may be package:http library. I do something like that:

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

  http.post(
    url,
    headers: {HttpHeaders.CONTENT_TYPE: "application/json"},
    body: {"foo": "bar"})
      .then((response) {
        print("Response status: ${response.statusCode}");
        print("Response body: ${response.body}");
      }).catchError((err) {
        print(err);
      });

,但出现以下错误:

Bad state: Cannot set the body fields of a Request with content-type "application/json".


推荐答案

来自 http.dart


/// [body] sets the body of the request. It can be a [String], a [List<int>] or
/// a [Map<String, String>]. If it's a String, it's encoded using [encoding] and
/// used as the body of the request. The content-type of the request will
/// default to "text/plain".


因此您自己生成JSON主体(使用 JSON.encode :转换)。

So generate the JSON body yourself (with JSON.encode from dart:convert).

这篇关于dart:io中具有json内容类型的Http POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆