post application/x-www-form-urlencoded Alamofire

为君一笑 提交于 2019-12-08 15:47:18

问题


I want to use Alamofire to retrieve a bearer token from Web API but I am new to ios and alamofire. How can I accomplish this with Alamofire?

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

回答1:


Well you don't really need Alamofire to do this (it can be simply done using a plain NSURLRequest) but here goes:

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

I think that the headers can be omitted since alamofire will append the appropriate Content-Type header. Let me know if it works.

You can also find a ton of specification with examples here.




回答2:


Here is example code that should work with Alamofire 4.x and Swift 3.x as of August 2017:

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

There is no need to set the content-type header explicitly, as it is set by Alamofire automatically.




回答3:


Alamofire 4.7.3 and Swift 4.0 above

As per the documentation for POST Request With URL-Encoded Parameters

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


来源:https://stackoverflow.com/questions/37177879/post-application-x-www-form-urlencoded-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!