Http POST在Postman中工作,但在Flutter中不工作

d8tt03nd  于 2023-06-22  发布在  Postman
关注(0)|答案(3)|浏览(200)

我尝试使用Http包在我的flutter应用程序上进行POST请求。我首先在API沙盒网站上测试了我的请求,然后在Postman中测试。它在那里工作得很好,但是一旦在Flutter中,我总是得到400 Bad Request。
下面是我在Flutter中的代码:

import 'package:http/http.dart';
import 'package:uuid/uuid.dart';
import 'package:wave_app/env/secrets.dart';
import 'package:wave_app/models/momo_token.dart';

    String url = "https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay";
    var uuid = Uuid();
    String requestId = uuid.v4();
    MomoToken token = await _createMomoNewTokenCollection();

    String auth = "Bearer " + token.accessToken;

    Map<String, String> headers = {
      "Authorization": auth,
      "X-Target-Environment": "sandbox",
      "X-Reference-Id": requestId,
      "Content-Type": "application/json",
      "Ocp-Apim-Subscription-Key": momoCollectionSubscriptionKey
    };

    String jsonBody = '{"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"}';

    Response response = await post(url, headers: headers, body: jsonBody);
    int statusCode = response.statusCode;

    print("STATUS CODE REQUEST TO PAY " + statusCode.toString());
    print(response.reasonPhrase.toString());
    print(response.body.toString());

    if (statusCode == 202) {
      return response.body.toString();
    } else {
      return null;
    }
  }

API文档在这里:https://momodeveloper.mtn.com/docs/services/collection/operations/requesttopay-POST
下面是我的Postman请求的curl代码(使用与requestId、auth、momoCollectionSubscriptionKey相同的变量)

curl --request POST \
  --url https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay \
  --header 'Accept: */*' \
  --header 'Accept-Encoding: gzip, deflate' \
  --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSMjU2In0.eyJjbGllbnRJZCI6IjFmY2MzMjBhLTM0NWQtMTFlYS04NTBkLTJlNzI4Y2U4ODEyNSIsImV4cGlyZXMiOiIyMDIwLTAxLTExVDE1OjU3OjE4Ljc3NyIsInNlc3Npb25JZCI6ImZmYzc1OGE2LTM2MWEtNDM4ZS1hYjE5LWQ1ZGQ4ZmU4ZjEyOSJ9.DeoJyU6Hb0he_or1XeBxW-6s-xwdtmi0cUrYjQe0Z796bIGvvT-VJ214JaZItG-CBQpgv7dHbLfXNqr8D05Q7U9XiOtpr8mtYWQlY-MseGIHAyxp1qBuQkwjmBYBlDxQOYYfzG9SZ8tGFUI1_k59LMNYIhDlXXKa68Ym1sylZ8wfWjGuHaKVzMEH25ubiBwCLev5IHPchuF3toVP99U-HC8t95E3zrEt9dHgzn0hnwvpB31wcsu_b3vb-YZ1idHgosPc2GmKFsDruX14VniKBicCsnGHqZAkSPXwaOR6SIn4JZEEwhAIj3Oe2H5dwxloiX5rzaApdkwEg6KSoBXk8A' \
  --header 'Cache-Control: no-cache' \
  --header 'Connection: keep-alive' \
  --header 'Content-Length: 194' \
  --header 'Content-Type: application/json' \
  --header 'Host: sandbox.momodeveloper.mtn.com' \
  --header 'Ocp-Apim-Subscription-Key: 281eb****************' \
  --header 'Postman-Token: ece19062-1f0b-4873-a3ed-1bd4ada8746a,528004b2-410d-4653-9909-5197a3dc95db' \
  --header 'User-Agent: PostmanRuntime/7.20.1' \
  --header 'X-Reference-Id: 062f8aad-f529-4d0a-804c-affb888c2b8b' \
  --header 'X-Target-Environment: sandbox' \
  --header 'cache-control: no-cache' \
  --data '{\r\n  "amount": "5",\r\n  "currency": "EUR",\r\n  "externalId": "123",\r\n  "payer": {\r\n    "partyIdType": "MSISDN",\r\n    "partyId": "46733123454"\r\n  },\r\n  "payerMessage": "hi",\r\n  "payeeNote": "hi"\r\n}'

在 Postman 和他们的网站上,我总是得到一个202接受的回应。我不知道我做错了什么。任何帮助将不胜感激!
------------编辑-----------------
我也试过使用HttpClient,这里是代码,但仍然得到400 Bad Request

HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));

    request.headers.set("Authorization", "Bearer " + token.accessToken);
    request.headers.set('content-type', 'application/json');
    request.headers.set("X-Target-Environment", "sandbox");
    request.headers.set("X-Reference-Id", requestId);
    request.headers.set("Ocp-Apim-Subscription-Key", momoCollectionSubscriptionKey);

    request.add(utf8.encode(jsonBody));
    HttpClientResponse response = await request.close();

    print("STATUS CODE " + response.statusCode.toString() + "   " + response.reasonPhrase);
    String reply = await response.transform(utf8.decoder).join();
    print("REPLY " + reply);
    httpClient.close();
ndh0cuux

ndh0cuux1#

这肯定是服务器的问题。两个头X-Reference-IdX-Target-Environment由服务器区分大小写处理(即它不符合RFC)。
Dart的io.HttpClient强制标头小写,因此这会影响package:httppackage:dio,它们都依赖于它。有一个request允许客户端保留头的大小写,但它的进展缓慢,因为它是一个突破性的变化。
同时,尝试使用保留头大小写的客户端分支。https://pub.dev/packages/alt_http/

jhdbpxl9

jhdbpxl92#

我通过添加这个头来解决我的问题:

'content-type': 'multipart/form-data'
qvtsj1bj

qvtsj1bj3#

通过将jsonBody从String更改为Map解决了相同的问题。

String jsonBody = '{"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"}';

只有从String -> Map改变才能解决;

Map jsonBody = {"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"};

此外,还包含了 jsonEncode
响应response = await post(url,headers:标题,正文:jsonEncode(jsonBody));
jsonEncode需要导入 Convert library

import 'dart:convert';

相关问题