Flutter: Send JSON body for Http GET request

后端 未结 2 479
借酒劲吻你
借酒劲吻你 2020-12-19 04:44

I need to make a GET request to an API from my Flutter app which requires request body as JSON (raw).

I tested the API with JSON request body in Postman and it seems

2条回答
  •  遥遥无期
    2020-12-19 05:33

    This answer is clarification for future visitors.

    GET

    GET requests are not intended for sending data to the server (but see this). That's why the http.dart get method doesn't have a body parameter. However, when you want to specify what you are getting from the server, sometimes you need to include query parameters, which is a form of data. The query parameters are key-value pairs, so you can include them as a map like this:

    final queryParameters = {
      'name': 'Bob',
      'age': '87',
    };
    final uri = Uri.http('www.example.com', '/path', queryParameters);
    final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
    final response = await http.get(uri, headers: headers);
    

    POST

    Unlike GET requests, POST requests are intended for sending data in the body. You can do it like this:

    final body = {
      'name': 'Bob',
      'age': '87',
    };
    final jsonString = json.encode(body);
    final uri = Uri.http('www.example.com', '/path');
    final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
    final response = await http.post(uri, headers: headers, body: jsonString);
    

    Note that the parameters were a Map on the Dart side. Then they were converted to a JSON string by the json.encode() function from the dart:convert library. That string is the POST body.

    So if the server is asking you to pass it data in a GET request body, check again. While it is possible to design a server in this way, it isn't standard.

提交回复
热议问题