这是我向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);

  });
  }

I have a problem with the response from the request, where its suppose to have a body with json, but something went wrong and i think is with the json that i send on the body request, because it is a nested json object, and the value of the key is a json object. i would love to know how i can parse the json right and insert into body of the request.

这是标题响应:

 {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}

and this is how is suppose to be:

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

the body response came empty and i think its because the body i sent on the request, can anyone help me with the nested json object in value??

SCREENSHOT OF POSTMAN:

推荐答案

好了,我们终于有了答案……

您正确地指定了headers: {"Content-Type": "application/json"},来设置您的内容类型.在引擎盖下面,包装http或下层dart:io HttpClient将其改变为application/json; charset=utf-8.但是,您的服务器Web应用程序显然不需要后缀.

To prove this I tried it in Java, with the two versions

conn.setRequestProperty("content-type", "application/json; charset=utf-8"); // fails
conn.setRequestProperty("content-type", "application/json"); // works

Are you able to contact the web application owner to explain their bug? I can't see where Dart is adding the suffix, but I'll look later.

EDIT Later investigation shows that it's the http package that, while doing a lot of the grunt work for you, is adding the suffix that your server dislikes. If you can't get them to fix the server then you can by-pass http and use the dart:io HttpClient directly. You end up with a bit of boilerplate which is normally handled for you by http.

工作示例如下:

import 'dart:convert';
import 'dart:io';
import 'dart:async';

main() async {
  String url =
      'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
  Map map = {
    'data': {'apikey': '12345678901234567890'},
  };

  print(await apiRequest(url, map));
}

Future<String> apiRequest(String url, Map jsonMap) async {
  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();
  // todo - you should check the response.statusCode
  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

Depending on your use case, it may be more efficient to re-use the HttpClient, rather than keep creating a new one for each request. Todo - add some error handling ;-)

Json相关问答推荐

如何形成正确的JQ表达式以从JSON文件中获得准确的输出数据?

如何在Vega中使标记的符号在鼠标指针悬停时可点击

在Vega中如何通过滑块改变条形图的宽度

使用 jq 将非统一的 json 输出转换为汇总表

从 oracle 数据库中的 json blob 打印值

使用 jq 和脚本 bash 映射两个 json

JOLT 在 struct 体中间添加一个 JSON 字段

在Flutter 中将 map 的 Json 转换为 list

python,将Json写入文件

Rails:format.js 或 format.json,或两者兼而有之?

编写 JSON 日志(log)文件的格式?

如何使用 Jackson 重命名 JSON 序列化中的根键

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

如何将有向无环图 (DAG) 存储为 JSON?

如何在 Rails 模型中验证字符串是否为 json

获取一个数字的 PHP 对象属性

雅虎财经全币种报价 API 文档

使用 axios 在 POST multipart/form-data 请求中发送文件和 json

类型是接口或抽象类,不能实例化