iOS Swift Http请求发布方法使用标头x-www-form-urlencoded吗?

时间:2018-07-11 04:38:09

标签: ios swift xcode alamofire nsurlsessiondatatask

我必须使用标头作为application/x-www-form-urlencoded值和JSON字符串的API调用。在邮递员中提供参数值和标头时,它可以正常工作并返回状态代码200正常。在这里,我正在使用后端node js。发布方法不适用于前端。不知道是什么问题。

错误:

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()

任何帮助都值得赞赏的人。

1 个答案:

答案 0 :(得分:0)

我看过您的代码,您想调用您为其创建的标头参数。您不是通过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

    }
   }

}