【问题标题】:Flutter - How to send a POST request using HTTP in Dart?Flutter - 如何在 Dart 中使用 HTTP 发送 POST 请求?
【发布时间】:2021-01-26 01:30:10
【问题描述】:

我正在使用将 HTTP 转换为 JSON 的 API 并从服务器获取响应,我需要发送 HTML 的发布请求,但我不知道该怎么做?

这是我当前的实现 -

Future<String> test() async {
  var link =
      await http.get('https://example.com');
  var body = parse(link.body);
  return body.outerHtml;
}

Future<Album> createAlbum(String html) async {
  final http.Response response = await http.post(
    'https://www.html2json.com/api/v1',
    headers: <String, String>{
      'Content-Type': 'text/html; charset=UTF-8',
    },
  
    body: html,
  );

  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to create album.');
  }
}

我称这是我的应用程序开始时这样,

@ovveride 
void initState() {
test().then((body) => createAlbum(body)); //Output returns HTTP error 301, am I doing something wrong?
super.initState();
}

【问题讨论】:

    标签: flutter http dart post


    【解决方案1】:

    检查了以下对我有用的代码。

    Future<Album> createAlbum(String html) async {
      final http.Response response = await http.post(
        'https://www.html2json.com/api/v1',
        headers: <String, String>{
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
      
        body: html,
      );
    

    您需要将内容类型更改为application/x-www-form-urlencoded; charset=UTF-8。这应该可以解决问题。

    【讨论】:

    • 你能把你要解析的html发给我吗?
    • 我在使用 google.com 时也遇到了同样的错误,你能试试吗?
    • loom.com/share/91e6907a9ca4446fa8f5990c7e4dc57b我为你制作了一个织机视频。检查一下。
    • 你能在github上分享你的整个代码吗?也许我错过了什么
    • 当然。我必须使用dio。对于请求处理,你可以使用任何你想要的。
    【解决方案2】:

    感谢 DARSH SHAH,我使用 dio (https://pub.dev/packages/dio) 解决了这个问题。

    dynamic response;
    
      Dio dio = Dio();
      Future<dynamic> test() async {
        dynamic link = await dio.get(
            'https://example.com');
        return link;
      }
    
      Future<dynamic> post(dynamic body) async {
        String _baseUrl = "https://html2json.com/api/v1";
        var options = Options(
          contentType: "application/x-www-form-urlencoded; charset=UTF-8",
          followRedirects: false,
        );
    
        final response = await dio.post(
          _baseUrl,
          data: body,
          options: options,
        );
        return response;
      }
    
    FloatingActionButton(
            onPressed: () async {
              dynamic responseHTML = await test();
              response = await post(responseHTML.data); //This will contain the JSON response
            },
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 2022-01-05
      • 2013-10-11
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多