Flutter-如何在Dart中使用HTTP发送POST请求?

时间:2020-10-11 15:42:12

标签: flutter http dart post

我正在使用将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();
}

2 个答案:

答案 0 :(得分:0)

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

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,
  );

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

答案 1 :(得分:0)

感谢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
        },
);