4

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Can you send me the html you want to parse?
I'm getting the same error even with google.com, can you try with that?
loom.com/share/91e6907a9ca4446fa8f5990c7e4dc57b I have made a loom video for you. Check that out.
Can you share your entire code on github? Maybe im missing something
Sure. I have to use dio. For request handling, you can use whatever you want.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.