使用标头x-www-form-urlencoded的iOS Swift Http请求发布方法?
Posted
技术标签:
【中文标题】使用标头x-www-form-urlencoded的iOS Swift Http请求发布方法?【英文标题】:iOS Swift Http request post method using header x-www-form-urlencoded? 【发布时间】:2018-07-11 04:38:08 【问题描述】:我必须使用作为 JSON 字符串的 application/x-www-form-urlencoded
值的标头进行 API 调用。在邮递员中给出参数值和标题时,它工作正常并返回状态码200
ok。我在这里使用后端 node js
。 Post 方法在前端不起作用。不知道是什么问题。
错误:
Sometimes i am getting request time out,
NSUrlfailingstring, finished with status code 1001
这是我的后端代码:
var status =
SUCCESS : 'success',
FAILURE : 'failure'
var httpStatus =
OK : HttpStatus.OK,
ISE : HttpStatus.INTERNAL_SERVER_ERROR,
BR : HttpStatus.BAD_REQUEST
exports.likes= function(req, res)
var Username =req.body.username;
var likecount=req.body.count;
var likedby = req.body.likedby;
var postId = req.body.postId;
var tokenId = req.body.tokenId;
var message =
to: tokenId,
collapse_key: '',
data:
name:Username,
Message:"Content about message",
Redirect:"TopostId : "+postId,
time: ""
,
notification:
title: "Hey Buddy , Someone have liked your post",
body: likedby +"Likedyourpost",
icon: "notification"
;
fcm.send(message)
.then(function (response)
console.log("Successfully sent with response: ", response);
res.status(httpStatus.OK).json(
status: status.SUCCESS,
code: httpStatus.OK,
error:''
);
return;
)
.catch(function (err)
console.log(err);
);
;
module.exports = function(app)
app.post('/likesnotification', notification.likes);
app.post('/commentsnotification', notification.comments);
app.post('/othernotification', notification.othernot);
app.post('/followrequset', notification.followreq);
app.post('/followresponse', notification.followres);
app.post('/publicaccountfollow', notification.publicacfollow);
;
这是我在 ios Swift 中的前端代码:
尝试 1:
func postNotification(postItem: String, post: Post)
print("Get token from post:::",post.token)
print(postItem)
let token = UserDefaults.standard.string(forKey: "token")
let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON (response:DataResponse<Any>) in
switch(response.result)
case .success(_):
if let data = response.result.value
print(data)
break
case .failure(_):
print(response.result.error as Any)
break
尝试 2:
var parameters = [String:Any]()
parameters["count"] = post.likeCount!
parameters["likedby"] = currentName
parameters["postId"] = postItem
parameters["token"] = post.token!
let Url = String(format: "http://highavenue.co:9000/likesnotification")
guard let serviceUrl = URL(string: Url) else return
// let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")
let parameterDictionary = parameters
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else
return
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) (data, response, error) in
if let response = response
print(response)
if let data = data
do
let json = try JSONSerialization.jsonObject(with: data, options:
[])
print(json)
catch
print(error)
.resume()
任何帮助都非常感谢。
【问题讨论】:
在后端检查,检查您是否正在获取数据? @PratikPrajapati 我在邮递员中获取数据 我的意思是,当您从设备/模拟器请求时,您是否获取数据 @PratikPrajapati 出现错误并出现错误 - 代码:-1001 可选(错误域=NSURLErrorDomain 代码=-1001“请求超时。” UserInfo=NSUnderlyingError=0x1c0e56920 错误域=kCFErrorDomainCFNetwork 代码= -1001 "(null)" UserInfo=_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4, NSErrorFailingURLStringKey=highavenue.co:9000/likesnotification, NSErrorFailingURLKey=highavenue.co:9000/likesnotification, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=请求超时。 ) 基于 Dipen Chudasama 的回答 @PratikPrajapati 是的,我正在获取数据 【参考方案1】:我看到了您的代码,您应该调用为它创建的标头参数。您没有在 alamofire 请求方法中传递标头。
如下:
let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON (response:DataResponse<Any>) in
switch(response.result)
case .success(_):
if let data = response.result.value
print(data)
break
case .failure(_):
print(response.result.error as Any)
break
【讨论】:
得到这样的错误并以错误结束 - 代码:-1001 可选(错误域 = NSURLErrorDomain 代码 = -1001“请求超时。” UserInfo = NSUnderlyingError = 0x1c0e56920 错误域 = kCFErrorDomainCFNetwork 代码 = -1001 "(null)" UserInfo=_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4, NSErrorFailingURLStringKey=highavenue.co:9000/likesnotification, NSErrorFailingURLKey=highavenue.co:9000/likesnotification, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=请求超时。 ) 你是否像我上面提到的那样在 alamo fire 方法中传递了该标头变量? 嘿,你能帮我解决这个问题吗 嘿,你能看看邮递员的截图吗....drive.google.com/file/d/1dmXvE2PoSnh9Dj0XVfGtMRu-IDKXETps/… 像这样传递标头:let headers = [ "Content-Type" : "application/x-www-form-urlencoded" ]以上是关于使用标头x-www-form-urlencoded的iOS Swift Http请求发布方法?的主要内容,如果未能解决你的问题,请参考以下文章
使用 apollo-datasource-rest 库将 Content-Type 标头设置为 application/x-www-form-urlencoded
无法修改标头信息 - 标头已在 Laravel AngularJS 中发送
带有 x-www-form-urlencoded 的 iOS Swift POST api