0

我正在制作post内容类型为application/x-www-form-urlencoded. 我无法在 post 方法中传递参数。下面是相关函数:

Future<ServerResponse> postAPICall(String apiName, Map<String, dynamic> params) async {
    var url = Webservices.baseUrl + version + apiName;
    var postUri = Uri.parse(url);

    var completer = Completer<ServerResponse>();
    HttpClient client = new HttpClient();
    client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
    HttpClientRequest request = await client.postUrl(postUri);
    request.headers.set("content-type", "application/x-www-form-urlencoded");
    request.headers.set("Authorization", Constant.authUser?.authToken == null
         ? ""
         : Constant.authUser.authToken);


    String jsonString = json.encode(params);
    String paramName = 'param';
    String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
    List<int> bodyBytes = utf8.encode(formBody);
    request.add(bodyBytes);
    HttpClientResponse response = await request.close();
    String data = await response.transform(utf8.decoder).join();
    var jsValue = json.decode(data);
    var serverResponseObj = ServerResponse.withJson(jsValue);
   completer.complete(serverResponseObj);
   return completer.future;
}
4

2 回答 2

0

我会使用http库:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FloatingActionButton(
        onPressed: () async {
          var response = await http.post(
            "https://postman-echo.com/post",
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            body: "foo1=bar1&foo2=bar2",
          );
          assert(response.statusCode == HttpStatus.ok);
        },
      ),
    );
  }
}
于 2020-05-22T14:39:37.157 回答
0

postUrl 方法接受一个 Uri 对象,如果您查看 Uri 的 API 文档,您会发现 Uri 接受查询或查询参数。所以你可以这样做:

client.postUrl(Uri.http('example.com', '/foo', {'username': 'john'}))

// or use Uri.https if server use https
client.postUrl(Uri.https('example.com', '/foo', {'username': 'john'})) 
于 2020-05-22T14:09:24.907 回答