在swift 3.2中使用json和header请求AFNetworking

时间:2017-10-16 15:11:38

标签: ios swift afnetworking

let header = [
            "Content-Type":"application/json",
            "X-Source":"iOS",
            "Authorization":token]
let strURL = "ValidURL"


let manager = AFHTTPSessionManager()
let serializer = AFHTTPRequestSerializer()
    for (_,dict) in header.enumerated() {
        serializer.setValue("\(dict.value)", forHTTPHeaderField: "\(dict.key)")
    }
    manager.requestSerializer = serializer

   let req = serializer.request(withMethod: "POST", urlString: strURL, parameters: params, error: nil)
   manager.dataTask(with: req as URLRequest) { (response, data, error) in
        print(error)
        print(response)
        print(data)
    }
//No response from this method

此外,我尝试过:

var request = URLRequest(url: URL(string: strURL)!)
request.httpMethod = "POST"
for (_,dict) in header.enumerated() {
        request.setValue("\(dict.value)", forHTTPHeaderField: "\(dict.key)")
    }
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
manager.dataTask(with: request) { (response, data, error) in
     print(error)
     print(response)
     print(data)
}

即使我尝试过:

manager.post(strURL, parameters: params, progress: nil, success: { (sessionTask, respose) in
            if let dict = respose as? Dictionary<String,Any> {
                print(dict)
            } else {
            }
        }) { (task, error) in
            print(error)
        }

//It Give me: failed: bad request (400)

1 个答案:

答案 0 :(得分:1)

这里有两个问题

  1. 使用dataTask方法时,会返回一个任务对象。当您希望发送请求时,需要在其上调用params

  2. 您的错误表明您的JSON正文不正确。那是在您的@angular/对象中,可能与服务期望的内容不匹配。