How to make HTTP POST request with url encoded body in flutter?

前端 未结 8 1351
南笙
南笙 2020-12-01 03:59

I\'m trying to make an post request in flutter with content type as url encoded. When I write body : json.encode(data), it encodes to plain text.

If I

相关标签:
8条回答
  • 2020-12-01 04:19

    I'd like to recommend dio package to you , dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

    dio is very easy to use, in your case you can:

    Map<String, String> body = {
    'name': 'doodle',
    'color': 'blue',
    'teamJson': {
      'homeTeam': {'team': 'Team A'},
      'awayTeam': {'team': 'Team B'},
      },
    };
    
    dio.post("/info",data:body, options: 
      new Options(contentType:ContentType.parse("application/x-www-form-urlencoded")))    
    

    dio can encode the data automatically.

    More details please refer to dio.

    0 讨论(0)
  • 2020-12-01 04:25

    I did it like this with dart's http package. It's not too fancy. My endpoint wasn't accepting the parameters with other methods, but it accepted them like this, with the brackets included in the parameter.

    import 'package:http/http.dart' as http;
    
    String url = "<URL>";
    
    Map<String, String> match = {
      "homeTeam[team]": "Team A",
      "awayTeam[team]": "Team B",
    };
    
    Map<String, String> headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    
    http.post(url, body: body, headers: headers).then((response){
        print(response.toString());
    });
    
    0 讨论(0)
提交回复
热议问题