【发布时间】:2018-10-21 00:58:44
【问题描述】:
这是我向 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 对象值吗??
邮递员的屏幕截图:
【问题讨论】:
-
你的变量是有意命名的
url和uri吗? -
如果您使用
json.encode(...),您发送的不是 JSON 字符串。如果您希望将其视为 JSON,只需直接发送{ 'data': { 'xpto': '12345678901234567890' } }。 -
@GünterZöchbauer 如果我这样做,会发生这种情况:E/flutter(1805):[ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] 未处理的异常:E/flutter( 1805):错误状态:无法设置内容类型为“application/json”的请求的正文字段。 E/flutter (1805): #0 Request.bodyFields= (package:http/src/request.dart:124:7) E/flutter (1805): #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart :165:17) E/flutter (1805): E/flutter (1805): #2 BaseClient.post (package:http/src/base_client.dart:56:5) ...
-
给了我这个错误:E/flutter (1805): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] 未处理的异常:E/flutter (1805): type ' _InternalLinkedHashMap
' 不是类型转换中“String”类型的子类型,其中 E/flutter(1805):_InternalLinkedHashMap 来自 dart:collection E/flutter(1805):String 来自 dart:core E/flutter( 1805): 字符串来自 dart:core E/flutter (1805): 字符串来自 dart:core -
“如果你使用 json.encode(...) 你发送一个字符串而不是 JSON”谢谢@GünterZöchbauer,我使用的是 json.encode(...),被删除了,现在我得到相应的响应!