我正在尝试使用IONIC 3的HTTP native将JSON数组作为参数发送。这是请求:
HTTPResponse = await this.http.post(url,
body, headers);
这是完整的代码。我正在使用来自'@ ionic-native / http'的HTTP。这是完整的代码
import { HTTP, HTTPResponse } from '@ionic-native/http';
[...]
let body = '[{"userId": 1, "timestamp":"2018-10-12T18:00:00.000+02",
"audit":"MENUTEST"},{"userId": 1, "timestamp":"2018-10-
12T18:00:00.000+02", "audit":"MENUTEST"},{"userId": 1,
"timestamp":"2018-10-12T18:00:00.000+02", "audit":"MENUTEST"}]';
//Auth header
let headers = { Authorization: `Bearer ${token}`};
let httpResponse: HTTPResponse = await
this.http.post(URL_data, JSON.parse(body), headers);
我正在使用类似的代码和其他请求,一切都很顺利,唯一的区别是正在进行的请求在JSON体中有一个简单的参数。这是一个很好的要求:
import { HTTP, HTTPResponse } from '@ionic-native/http';
[...]
let body = '{ "username": "usuario.prueba1", "password": "' +
Md5.hashStr('prueba') + '", "customerCode": "1234DEV" }';
let httpResponse: HTTPResponse = await
this.http.post(URL_login, JSON.parse(body), headers);
答案 0 :(得分:0)
更新回答:
如果您查看post动作的android实现的source-file,您将看到JsonObject需要作为参数,这就是为什么传递数组将导致JSON error
。您必须将数组包装在这样的对象中才能使其工作:
let body = {
myArray: [
{
userId: 1,
timestamp: '2018-10-12T18:00:00.000+02',
audit: 'MENUTEST',
},
{
userId: 1,
timestamp: '2018-10-12T18:00:00.000+02',
audit: 'MENUTEST',
},
{
userId: 1,
timestamp: '2018-10-12T18:00:00.000+02',
audit: 'MENUTEST',
},
],
};
let headers = { Authorization: `Bearer ${token}` };
let httpResponse: HTTPResponse = await this.http.post(
URL_data,
body,
headers,
);
旧回答:
我猜您的Content-Type
为application/x-www-form-urlencoded
,因此您需要为您的参数添加一个名称,该名称与该值以等号(=
)分隔:
let payload = [{ "userId": 3, "timestamp": "2018-10-12T18:00:00.000+02", "audit": "Mensaje 3" }, { "userId": 4, "timestamp": "2018-10-13T18:00:00.000+02", "audit": "Mensaje 4" }];
let body = `MyArray=${payload}`;
可以找到规范的相关部分here。第2点说:
控件名称/值按它们在文档中出现的顺序列出。名称通过“=”与值分隔,名称/值对通过“&”分隔。
答案 1 :(得分:-1)
要支持深层结构,您应该更改序列化程序。
尝试设置http.setDataSerializer("json");
并照常发送数据:http.post(url, body, {})