gpt4 book ai didi

javascript - Nodejs http.request 如何将 json 参数发送到 java 接口(interface)

转载 作者:行者123 更新时间:2023-11-30 01:44:22 24 4
gpt4 key购买 nike

我们有一个java接口(interface)来发送verify_code到手机,并且在postman上工作得很好。

postman

我的nodejs代码如下

let test = {
"phoneNumber": "15021071273",
"smsParams": [
"注册",
"123456",
"注册"
],
"tmplId": 109341
}

var content = JSON.stringify(test);

// An object of options to indicate where to post to
var post_options = {
host: '172.16.211.33', //'common-message'
port: '10011',
path: '/sms/sendTecentyunSms',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': content.length
}
};

// Set up the request
var post_req = http.request(post_options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});

// post the data
post_req.write(content);
post_req.end();

和java接口(interface)响应:

Response: {"timestamp":1572935973619,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"JSON parse error: Unexpected end-of-input within/between Object entries; nested exception is com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input within/between Object entries\n at [Source: java.io.PushbackInputStream@3e497877; line: 1, column: 157]","path":"/sms/sendTecentyunSms"}

看起来这只是一个 json 解析错误。

我还尝试先对 tese.smsParams 进行 JSON.stringy,但不起作用

req.write 只接受字符串或缓冲区,因此它不能只将 json 对象作为参数。

最佳答案

请尝试这个方法

var http = require('http')

var body = JSON.stringify({
"phoneNumber": "15021071273",
"smsParams": [
"注册",
"123456",
"注册"
],
"tmplId": 109341
})

var request = new http.ClientRequest({
hostname: "172.16.211.33",
port: 10011,
path: "/sms/sendTecentyunSms",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})

request.end(body)


request.on('response', function (response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});

关于javascript - Nodejs http.request 如何将 json 参数发送到 java 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com