首页 > 解决方案 > Flutter - 如何在 Dart 中使用 HTTP 发送 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();
}

标签: flutterhttpdartpost

解决方案


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

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. 这应该可以解决问题。


推荐阅读