post application / x-www-form-urlencoded Alamofire

时间:2016-05-12 05:19:24

标签: ios swift2 alamofire

我想使用Alamofire从Web API检索持有者令牌,但我是ios和alamofire的新手。我怎样才能用Alamofire来实现这个目标?

func executeURLEncodedRequest(url: URL, model: [String : String]?, handler: RequestHandlerProtocol) {
    addAuthorizationHeader()
    Alamofire.request(.POST,createUrl(url), parameters: model, headers: headers,encoding:.Json)
}

3 个答案:

答案 0 :(得分:22)

嗯,你真的不需要Alamofire这样做(可以简单地使用普通的NSURLRequest来完成)但是这里有:

let headers = [
    "Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
    "myParameter": "value"
]
let url = NSURL(string: "https://something.com")!
Alamofire.request(.POST, url, parameters: parameters, headers: headers, encoding: .URLEncodedInURL).response { request, response, data, error in
    print(request)
    print(response)
    print(data)
    print(error)
}

我认为标题可以省略,因为alamofire会附加相应的Content-Type标题。如果有效,请告诉我。

您还可以找到大量的规范with examples here

答案 1 :(得分:9)

以下是截至2017年8月应与Alamofire 4.x和Swift 3.x配合使用的示例代码:

let parameters = [
  "myParameter": "value"
]
Alamofire.request("https://something.com", method: .post, parameters: parameters, encoding: URLEncoding()).response { response in
  print(response.request)
  print(response.response)
  print(response.data)
  print(response.error)
}

无需明确设置内容类型标头,因为它是由Alamofire自动设置的。

答案 2 :(得分:2)

Alamofire 4.7.3和更高版本的Swift 4.0

根据documentation进行的带有URL编码参数的POST请求

let parameters: Parameters = [
    "foo": "bar", 
    "val": 1 
]

// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

// HTTP body: foo=bar&val=1