How to do POST in Dart command line HttpClient

后端 未结 2 971
盖世英雄少女心
盖世英雄少女心 2021-01-12 13:22

I\'m struggling with putting together a Dart command line client capable of doing http POST. I know that I can not use dart:html library and have to use dart:io

The

相关标签:
2条回答
  • 2021-01-12 14:12

    I'd like to recommend dio package to you , dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

    dio is very easy to use:

    Performing a Get request:

    response=await dio.get(url)
    

    Performing a POST request:

    response=await dio.post(url,data:{"id":12,"name":"wendu"})
    

    Sending FormData:

    FormData formData = new FormData.from({
       "name": "wendux",
       "file1": new UploadFileInfo(new File("./upload.pdf"), "upload1.pdf")
    });
    response = await dio.post("/info", data: formData)
    

    Downloading a file:

    response=await dio.download("https://www.google.com/","./xx.html") 
    

    More details please refer to dio in Github: https://github.com/flutterchina/dio.

    0 讨论(0)
  • 2021-01-12 14:26

    use http package and dart:convert

    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    void main() {
    
    
      var url = 'http://httpbin.org/post';
      http.post(url, body: JSON.encode({'test': 'value'})).then((response) {
        print("Response status: ${response.statusCode}");
        print("Response body: ${response.body}");
      });
    }
    

    For adding custom headers, handling errors etc. see https://www.dartlang.org/dart-by-example/#making-a-post-request

    0 讨论(0)
提交回复
热议问题