json - 主体上带有 Json 的 HTTP POST - Flutter/Dart

这是我向 API 发出请求的代码:

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
  var body = jsonEncode({ 'data': { 'apikey': '12345678901234567890' } });

  print("Body: " + body);

  http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  ).then((http.Response response) {
    print("Response status: ${response.statusCode}");
    print("Response body: ${response.contentLength}");
    print(response.headers);
    print(response.request);

  });
  }

我对请求的响应有疑问,它假设有一个带有 json 的正文,但是出了点问题,我认为是我在正文请求中发送的 json,因为它是一个嵌套的 json 对象, 键的值是一个 json 对象。我很想知道如何正确解析 json 并插入到请求的正文中。

这是标题响应:

 {set-cookie: JSESSIONID=DA65FBCBA2796D173F8C8D78AD87F9AD;path=/testes2/;HttpOnly, last-modified: Thu, 10 May 2018 17:15:13 GMT, cache-control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0, date: Thu, 10 May 2018 17:15:13 GMT, content-length: 0, pragma: no-cache, content-type: text/html, server: Apache-Coyote/1.1, expires: Tue, 03 Jul 2001 06:00:00 GMT}

这是应该的:

Server: Apache-Coyote/1.1
Expires: Tue, 03 Jul 2001 06:00:00 GMT
Last-Modified: Thu, 10 May 2018 17:17:07 GMT
Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Vary: Accept-Encoding
Set-Cookie: JSESSIONID=84813CC68E0E8EA6021CB0B4C2F245BC;path=/testes2/;HttpOnly
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked

正文响应为空,我认为这是因为我在请求中发送的正文,任何人都可以帮助我处理嵌套的 json 对象值吗??

postman 的屏幕截图:

最佳答案

这行得通!

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

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

https://stackoverflow.com/questions/50278258/

相关文章:

ios - 使用 Flutter 在 Windows 环境下开发 iOS 设备

dart - 如何在 flutter 中使用 url 编码的主体发出 HTTP POST 请求?

function - 如何在 Dart/Flutter 中使用另一个文件的函数?

flutter - 未找到 Material 小部件

json - 如何在 Flutter 中解码 JSON?

gridview - 如何在 Flutter 的 GridView 中为 Widget 设置自定义高

dart - 如何使用 Flutter 在 iOS 和 Android 上共享图像?

dart - 如何在 Flutter 中更改键盘上的文本输入操作按钮(返回/回车键)?

java - Flutter 应用程序体积太大

flutter - 如何修复 HttpException : Connection closed b