我有一个端点可以在Postman中工作,但不能在Flutter中工作

时间:2019-09-26 13:42:35

标签: json http post flutter dart

我将此代码发送到我的端点

 {
"currency":"BTC",
"payment_slips":[{"number":"11111.11111 11111.111111 11111.111111 1 11111111111111","institution":"itau","amount":50.5,"due_date":"20/08/2018","personal_id":"00000000000","name":"Douglas"}],
"mobile_recharges":[],
"direct_transfers":[],
"digital_products":[],
"card_recharge":[],
"hugpay":[]
}

它不起作用,但是当我在邮递员身上寄出相同的尸体时,它的工作

我如何在列表中添加itens

  incrementListPaymentSlipes(PaymentSlipes objPayment) async {
    objPayment.name = "Douglas";
    objPayment.personalId = "00000000000";
    // var json = objPayment.toJson();
    listPaymentSlipes.add(objPayment);
  }
List listMobileRecharges = [];
List listPaymentSlipes = [];
List listDirectTransfers = [];
List listDigitalProducts = [];
List listCardRecharge = [];
List listHugpay = [];
String currencyCoin;

myBody

 var body = jsonEncode({
    "currency": currencyCoin,
    "payment_slips": listPaymentSlipes,
    "mobile_recharges": listMobileRecharges,
    "direct_transfers": listDirectTransfers,
    "digital_products": listDigitalProducts,
    "card_recharge": listCardRecharge,
    "hugpay": listHugpay
  });

发出请求的功能

ordersCreate() async {

    //RECUPERANDO O TOKEN DO SHAREDPREFERENCES
    final prefs = await SharedPreferences.getInstance();
    String token = prefs.getString("TOKEN");
    //RECUPERANDO O TOKEN DO SHAREDPREFERENCES

    String url = "https://sandbox-kmp.kamoney.com.br/orders";

    var response = await http.post(url,
        body: body,
        headers: {          
          HttpHeaders.authorizationHeader: "Bearer $token"
          ,
          "Accept": "application/json",
          "Content-Type": "application/x-www-form-urlencoded",
        },
        encoding: Encoding.getByName("utf-8"));
    if (response.statusCode == 200) {
      print("Feito");
      // print(response.statusCode.toString());
    } else {
      print(response.body);
      print(body);
    }
  }

{“错误”:“'currency'-obrigatório”,“代码”:“ currency_required”}

3 个答案:

答案 0 :(得分:0)

您可以将json字符串粘贴到https://app.quicktype.io/,您将获得正确的结构

使用以下代码段即可获取正确的json字符串

PaymentSlip paymentSlip = PaymentSlip(
      number: "11111.11111 11111.111111 11111.111111 1 11111111111111",
      institution: "itau",
      amount: 50.5,
      dueDate: "20/08/2018",
      personalId: "00000000000",
      name: "Douglas");
  List<PaymentSlip> paymentSlipList = [];
  paymentSlipList.add(paymentSlip);

  Payment payment = Payment(
      currency: "BTC",
      paymentSlips: paymentSlipList,
      mobileRecharges: [],
      directTransfers: [],
      digitalProducts: [],
      cardRecharge: [],
      hugpay: []);

  String jsonStr = paymentToJson(payment);
  print('${jsonStr}');

相关的类文件

// To parse this JSON data, do
//
//     final payment = paymentFromJson(jsonString);

import 'dart:convert';

Payment paymentFromJson(String str) => Payment.fromJson(json.decode(str));

String paymentToJson(Payment data) => json.encode(data.toJson());

class Payment {
    String currency;
    List<PaymentSlip> paymentSlips;
    List<dynamic> mobileRecharges;
    List<dynamic> directTransfers;
    List<dynamic> digitalProducts;
    List<dynamic> cardRecharge;
    List<dynamic> hugpay;

    Payment({
        this.currency,
        this.paymentSlips,
        this.mobileRecharges,
        this.directTransfers,
        this.digitalProducts,
        this.cardRecharge,
        this.hugpay,
    });

    factory Payment.fromJson(Map<String, dynamic> json) => Payment(
        currency: json["currency"],
        paymentSlips: List<PaymentSlip>.from(json["payment_slips"].map((x) => PaymentSlip.fromJson(x))),
        mobileRecharges: List<dynamic>.from(json["mobile_recharges"].map((x) => x)),
        directTransfers: List<dynamic>.from(json["direct_transfers"].map((x) => x)),
        digitalProducts: List<dynamic>.from(json["digital_products"].map((x) => x)),
        cardRecharge: List<dynamic>.from(json["card_recharge"].map((x) => x)),
        hugpay: List<dynamic>.from(json["hugpay"].map((x) => x)),
    );

    Map<String, dynamic> toJson() => {
        "currency": currency,
        "payment_slips": List<dynamic>.from(paymentSlips.map((x) => x.toJson())),
        "mobile_recharges": List<dynamic>.from(mobileRecharges.map((x) => x)),
        "direct_transfers": List<dynamic>.from(directTransfers.map((x) => x)),
        "digital_products": List<dynamic>.from(digitalProducts.map((x) => x)),
        "card_recharge": List<dynamic>.from(cardRecharge.map((x) => x)),
        "hugpay": List<dynamic>.from(hugpay.map((x) => x)),
    };
}

class PaymentSlip {
    String number;
    String institution;
    double amount;
    String dueDate;
    String personalId;
    String name;

    PaymentSlip({
        this.number,
        this.institution,
        this.amount,
        this.dueDate,
        this.personalId,
        this.name,
    });

    factory PaymentSlip.fromJson(Map<String, dynamic> json) => PaymentSlip(
        number: json["number"],
        institution: json["institution"],
        amount: json["amount"].toDouble(),
        dueDate: json["due_date"],
        personalId: json["personal_id"],
        name: json["name"],
    );

    Map<String, dynamic> toJson() => {
        "number": number,
        "institution": institution,
        "amount": amount,
        "due_date": dueDate,
        "personal_id": personalId,
        "name": name,
    };
}

打印以下完整代码的结果

I/flutter (17376): {"currency":"BTC","payment_slips":[{"number":"11111.11111 11111.111111 11111.111111 1 11111111111111","institution":"itau","amount":50.5,"due_date":"20/08/2018","personal_id":"00000000000","name":"Douglas"}],"mobile_recharges":[],"direct_transfers":[],"digital_products":[],"card_recharge":[],"hugpay":[]}

完整代码

import 'package:flutter/material.dart';
// To parse this JSON data, do
//
//     final payment = paymentFromJson(jsonString);

import 'dart:convert';

Payment paymentFromJson(String str) => Payment.fromJson(json.decode(str));

String paymentToJson(Payment data) => json.encode(data.toJson());

class Payment {
  String currency;
  List<PaymentSlip> paymentSlips;
  List<dynamic> mobileRecharges;
  List<dynamic> directTransfers;
  List<dynamic> digitalProducts;
  List<dynamic> cardRecharge;
  List<dynamic> hugpay;

  Payment({
    this.currency,
    this.paymentSlips,
    this.mobileRecharges,
    this.directTransfers,
    this.digitalProducts,
    this.cardRecharge,
    this.hugpay,
  });

  factory Payment.fromJson(Map<String, dynamic> json) => Payment(
        currency: json["currency"],
        paymentSlips: List<PaymentSlip>.from(
            json["payment_slips"].map((x) => PaymentSlip.fromJson(x))),
        mobileRecharges:
            List<dynamic>.from(json["mobile_recharges"].map((x) => x)),
        directTransfers:
            List<dynamic>.from(json["direct_transfers"].map((x) => x)),
        digitalProducts:
            List<dynamic>.from(json["digital_products"].map((x) => x)),
        cardRecharge: List<dynamic>.from(json["card_recharge"].map((x) => x)),
        hugpay: List<dynamic>.from(json["hugpay"].map((x) => x)),
      );

  Map<String, dynamic> toJson() => {
        "currency": currency,
        "payment_slips":
            List<dynamic>.from(paymentSlips.map((x) => x.toJson())),
        "mobile_recharges": List<dynamic>.from(mobileRecharges.map((x) => x)),
        "direct_transfers": List<dynamic>.from(directTransfers.map((x) => x)),
        "digital_products": List<dynamic>.from(digitalProducts.map((x) => x)),
        "card_recharge": List<dynamic>.from(cardRecharge.map((x) => x)),
        "hugpay": List<dynamic>.from(hugpay.map((x) => x)),
      };
}

class PaymentSlip {
  String number;
  String institution;
  double amount;
  String dueDate;
  String personalId;
  String name;

  PaymentSlip({
    this.number,
    this.institution,
    this.amount,
    this.dueDate,
    this.personalId,
    this.name,
  });

  factory PaymentSlip.fromJson(Map<String, dynamic> json) => PaymentSlip(
        number: json["number"],
        institution: json["institution"],
        amount: json["amount"].toDouble(),
        dueDate: json["due_date"],
        personalId: json["personal_id"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "number": number,
        "institution": institution,
        "amount": amount,
        "due_date": dueDate,
        "personal_id": personalId,
        "name": name,
      };
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      PaymentSlip paymentSlip = PaymentSlip(
          number: "11111.11111 11111.111111 11111.111111 1 11111111111111",
          institution: "itau",
          amount: 50.5,
          dueDate: "20/08/2018",
          personalId: "00000000000",
          name: "Douglas");
      List<PaymentSlip> paymentSlipList = [];
      paymentSlipList.add(paymentSlip);

      Payment payment = Payment(
          currency: "BTC",
          paymentSlips: paymentSlipList,
          mobileRecharges: [],
          directTransfers: [],
          digitalProducts: [],
          cardRecharge: [],
          hugpay: []);

      String jsonStr = paymentToJson(payment);
      print('${jsonStr}');

      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

答案 1 :(得分:0)

我解决了将方法http转换为dio的问题

答案 2 :(得分:0)

如果您使用Do插件,它将起作用。 我认为Dio更易于使用。

它看起来像这样,只适合您的情况:

ordersCreate() async {

var dio = Dio();

FormData data = FormData();
data.add("currency", currencyCoin);
data.add("payment_slips", listPaymentSlipes.toString());
data.add("mobile_recharges", listMobileRecharges.toString());
data.add("direct_transfers", listDirectTransfers.toString());
data.add("digital_products", listDigitalProducts.toString());
data.add("card_recharge", listCardRecharge.toString());
data.add("hugpay", listHugpay.toString());

String url = "https://sandbox-kmp.kamoney.com.br/";

dio.options.baseUrl = url;

var response = await dio.post('orders',data: data);
if (response.statusCode == 200) {
  print("Feito");
  // print(response.statusCode.toString());
} else {
  print(data.toString());
  print(body);
}

}