4
votes

I am using an API that converts HTTP to JSON and to get a response from the server I need to send a post request of HTML however i'm not sure how to do that?

This is my current implementation -

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.');
  }
}

I call this is when my app starts like so,

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

2 Answers

0
votes

Checked the following code which worked for me.

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

You need to change the Content-type to application/x-www-form-urlencoded; charset=UTF-8. This should do the trick.

0
votes

Thanks to DARSH SHAH, I solved this using 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
        },
);