使用 URLSession 发布公钥字符串时出现超时错误
我正在创建 rsa 密钥对并将公钥发送到我的 api。但是 post 请求失败并出现超时错误。以下是我的请求函数:
func perform<T: Decodable>(reqData: Data, with completion: @escaping (T?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// insert json data to the request
request.httpBody = reqData
print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let error = error else {
print(error)
completion(nil)
return
}
guard let data = data else {
completion(nil)
return
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
completion(try? decoder.decode(T.self, from: data))
}
task.resume()
}
POST 中发送的 JSON 对象:
{
"publicKey" : "MIIBCgKCAQEA4lS13W+TXZhUXy5yB2NpeulCVb1ZSaReopeKrahjKmUx4NQxVXruEYCY3LpjZcSy8xiudVG3GBIMnPLtaMbc5WAYDj1M2OwnpNHdQ8SKtZ1tdA6iRjfOXGUa1n8FMIMKU5ynTSAiSoh+8gGrY0L6jTsCSdLO5ZU53LQFHSESM8JuBeNZozolb\/cKb38ylercVeVpo8egoA8UqHezK23VUJ23faxMmMZDJxVn5pfFedxBTLxwU65KQY8Z4izaFjuPLoGe5JZkXyYNMcrYloDCBG5m9BFiXVkoLEDmGFGfWLMJcqL+D2CszqJ4h712ZR6LYRNtIbo\/HG9KR7XCtap3QwIDAQAB"
}
我已经在 Postman 中测试了 url,它在那里工作得很好。但当我从我的应用程序调用它时,它给出了以下错误:
Task <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1> finished with error [-1001] Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSUnderlyingError=0x280299c50 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1>"
), NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=http://192.168.178.205:3000/savepublickey, NSErrorFailingURLKey=http://192.168.178.205:3000/savepublickey, _kCFStreamErrorDomainKey=4}
以下是 Node.js 中的服务器端代码:
app.post('/savepublickey', (req, res) => {
console.log("savepublickey");
console.log(req.body);
let data = JSON.parse(JSON.stringify(req.body, null, 2));
if (data['publicKey'] != null && data['publicKey'] != "") {
console.log("Success");
publicKey = data['publicKey'];
res.status(200).json({
"Status": "Success"
}).send();
} else {
console.log("Fail");
res.status(500).json({
"Status": "Invalid request"
}).send();
}
})
I am creating a rsa key pair and send the public key to my api. But the post request fails with Timeout error. Following is my function for the request:
func perform<T: Decodable>(reqData: Data, with completion: @escaping (T?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// insert json data to the request
request.httpBody = reqData
print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let error = error else {
print(error)
completion(nil)
return
}
guard let data = data else {
completion(nil)
return
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
completion(try? decoder.decode(T.self, from: data))
}
task.resume()
}
JSON Object sent in POST:
{
"publicKey" : "MIIBCgKCAQEA4lS13W+TXZhUXy5yB2NpeulCVb1ZSaReopeKrahjKmUx4NQxVXruEYCY3LpjZcSy8xiudVG3GBIMnPLtaMbc5WAYDj1M2OwnpNHdQ8SKtZ1tdA6iRjfOXGUa1n8FMIMKU5ynTSAiSoh+8gGrY0L6jTsCSdLO5ZU53LQFHSESM8JuBeNZozolb\/cKb38ylercVeVpo8egoA8UqHezK23VUJ23faxMmMZDJxVn5pfFedxBTLxwU65KQY8Z4izaFjuPLoGe5JZkXyYNMcrYloDCBG5m9BFiXVkoLEDmGFGfWLMJcqL+D2CszqJ4h712ZR6LYRNtIbo\/HG9KR7XCtap3QwIDAQAB"
}
I have tested the url in Postman and it works good there. But it is giving my follwoing error when I call it from my app:
Task <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1> finished with error [-1001] Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSUnderlyingError=0x280299c50 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1>"
), NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=http://192.168.178.205:3000/savepublickey, NSErrorFailingURLKey=http://192.168.178.205:3000/savepublickey, _kCFStreamErrorDomainKey=4}
Following is my server side code in Node.js:
app.post('/savepublickey', (req, res) => {
console.log("savepublickey");
console.log(req.body);
let data = JSON.parse(JSON.stringify(req.body, null, 2));
if (data['publicKey'] != null && data['publicKey'] != "") {
console.log("Success");
publicKey = data['publicKey'];
res.status(200).json({
"Status": "Success"
}).send();
} else {
console.log("Fail");
res.status(500).json({
"Status": "Invalid request"
}).send();
}
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论