Home > Mobile >  Flutter post request do not send parameters
Flutter post request do not send parameters

Time:01-02

Here is my code, when I post the request, It just send http://10.0.2.2:43213/api/User/InsertNewUser as response.request and so do not put the body. However, I need to send something like that http://10.0.2.2:43213/api/User/InsertNewUser?userName=test&[email protected]&userPassword=test123 How can I post the parameters?

          Future<http.Response> postRequest () async {
              var url = Uri.parse('http://10.0.2.2:43213/api/User/InsertNewUser');

              Map data = {
                'userName': 'test',
                'userEmail': '[email protected]',
                'userPassword': 'test123'
              };
              //encode Map to JSON
              var body = json.encode(data);
              
              var response = await http.post(url,
                  headers: {"Content-Type": "application/json"},
                  body: body
              );

              return response;

        }

CodePudding user response:

It seems from your comment that you do not want to JSON encode the parameters, so don't!

Change:

          //encode Map to JSON
          var body = json.encode(data);
          
          var response = await http.post(url,
              headers: {"Content-Type": "application/json"},
              body: body
          );

to

          final response = await http.post(url, body: body);

http will then form encode your map and set the correct content type.

Adding the parameters to the URL (as you've done in the edit) would be used with a GET (rather than a POST). If you'd prefer that simply format your URL with the parameters as follows:

          final data = {
            'userName': 'test',
            'userEmail': '[email protected]',
            'userPassword': 'test123'
          };

          final url = Uri.http('10.0.2.2:43213', '/api/User/InsertNewUser', data);
          
          final response = await http.get(url);

CodePudding user response:

You can try this;

  Future<http.Response> postRequest () async {

 var url = Uri.parse('http://10.0.2.2:43213/api/User/InsertNewUser');

    Object myBody(){
      var theBody = jsonEncode(
              {
                'userName': 'test',
                'userEmail': '[email protected]',
                'userPassword': 'test123'
              });
      return theBody;
    }

 var response = await http.post(url,
                  headers: {"Content-Type": "application/json"},
                  body: myBody()
              );

              return response;
}
  • Related