一、方法封装
//post json数据
//返回json格式字符串
exports.postJson = function (url, data, fn) {
var deferred;
if (fn === undefined)
deferred = Q.defer();
data = data || {};
var content = JSON.stringify(data);
var options = {
host: url.host,
port: url.port,
path: url.path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(content)
}
};
var req = http.request(options, function (res) {
var result = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
result += chunk;
});
res.on('end', function () {
result = result ? JSON.parse(result) : false;
if (fn === undefined) {
deferred.resolve(result);
} else {
fn(result);
}
});
});
req.on('error', function (e) {
if (fn === undefined) {
deferred.reject('Post Error:' + e.message);
} else {
console.log('Get Error:' + e.message);
}
});
req.write(content);
req.end();
if (fn === undefined)
return deferred.promise;
};
exports.createSettleOrder = function (setleOrderParam, callback) {
var url = appConfig.operation("createSettleOrder", undefined);
console.log(url);
utils.postJson(url, setleOrderParam, function (data) {
callback(data);
});
};
var settleOrderParam = {
productId: 1496
};
settleService.createSettleOrder(settleOrderParam, function (data) {
console.log(data);
});
四、结论
不管什么语言调用java rest api都是可以直接传递复杂对象的,关键是content-type需要设置为application/json.
五、后传
那么rest client如何传递复杂对象呢
1、添加header
2、body传递json字符串