如何 POST 在 Swift 中请求
How to POST request in Swift
我有这个APIhttp://my-api.mydoctorfinder.com/
这将 return 一个布尔值,具体取决于您输入的电子邮件和密码。
我的问题是尽管使用了正确的电子邮件和密码,它总是 return 错误。
我在想我可能没有发送正确的参数,因为我创建了一个包含电子邮件和密码的字典。然后通过NSJSONSerialization.dataWithJSONObject方法
顺便说一下,我使用的是 SwiftyJson。
这是我的代码
//creates a dictionary and calls the PostRequest method
func attemptLogIn( email: String, password: String) {
let route = loggerURL
let body: [String:String] = ["email":email, "password":password]
makeHTTPPostRequest(route, body: body)
}
//performs post request
private func makeHTTPPostRequest(path: String, body: [String: AnyObject]) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
//onCompletion(json, nil)
print("The Response: ")
print(json)
} else {
//onCompletion(nil, error)
print("The Response: ")
print("Hello")
}
})
task.resume()
} catch {
// Create your personal error
//onCompletion(nil, nil)
}
}
- 检查您的电子邮件和密码密钥以及 API 所需的输入
- 检查您的登录信息URL
尝试以这种方式使用 NSJSON序列化创建 JSON 对象:
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
我认为问题出在 .PrettyPrinted 常量中。
编辑:
也尝试添加正确的内容类型:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
这里是 swift post 获取数据的请求:
func retriveTextDataByPost(requestURL:String, params: NSDictionary, handler:((dict:NSDictionary?) -> Void)) {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let url = NSURL(string: requestURL)
let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
do {
let postData = try NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted)
request.HTTPBody = postData
let postDataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if data != nil {
do {
let dictResult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
handler(dict: dictResult)
} catch { }
}
}
postDataTask.resume()
} catch { }
}
响应只是真或假,即它不是 json 对象。
所以我建议不要使用 Swifty 儿子,而是使用 Alamofire。
以下代码应该适合您:-
let myParameters = [
"email": "your email id",
"password": "your password"]
Alamofire.request(.POST, "http://my-api.mydoctorfinder.com/ ", parameters: myParameters)
.response { request, response, data, error in
print(request)
print(response)
if(response == true)
{
// do your thing
}
print(error)
}
注意:可能需要对 bool
的响应进行类型转换
以下是您提供的 link 的屏幕截图,它 returns 正确(而不是 json 对象)[注册后,我尝试使用相同的凭据登录]
我有这个APIhttp://my-api.mydoctorfinder.com/ 这将 return 一个布尔值,具体取决于您输入的电子邮件和密码。
我的问题是尽管使用了正确的电子邮件和密码,它总是 return 错误。
我在想我可能没有发送正确的参数,因为我创建了一个包含电子邮件和密码的字典。然后通过NSJSONSerialization.dataWithJSONObject方法
顺便说一下,我使用的是 SwiftyJson。
这是我的代码
//creates a dictionary and calls the PostRequest method
func attemptLogIn( email: String, password: String) {
let route = loggerURL
let body: [String:String] = ["email":email, "password":password]
makeHTTPPostRequest(route, body: body)
}
//performs post request
private func makeHTTPPostRequest(path: String, body: [String: AnyObject]) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
//onCompletion(json, nil)
print("The Response: ")
print(json)
} else {
//onCompletion(nil, error)
print("The Response: ")
print("Hello")
}
})
task.resume()
} catch {
// Create your personal error
//onCompletion(nil, nil)
}
}
- 检查您的电子邮件和密码密钥以及 API 所需的输入
- 检查您的登录信息URL
尝试以这种方式使用 NSJSON序列化创建 JSON 对象:
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
我认为问题出在 .PrettyPrinted 常量中。
编辑: 也尝试添加正确的内容类型:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
这里是 swift post 获取数据的请求:
func retriveTextDataByPost(requestURL:String, params: NSDictionary, handler:((dict:NSDictionary?) -> Void)) {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let url = NSURL(string: requestURL)
let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
do {
let postData = try NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted)
request.HTTPBody = postData
let postDataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if data != nil {
do {
let dictResult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
handler(dict: dictResult)
} catch { }
}
}
postDataTask.resume()
} catch { }
}
响应只是真或假,即它不是 json 对象。 所以我建议不要使用 Swifty 儿子,而是使用 Alamofire。
以下代码应该适合您:-
let myParameters = [
"email": "your email id",
"password": "your password"]
Alamofire.request(.POST, "http://my-api.mydoctorfinder.com/ ", parameters: myParameters)
.response { request, response, data, error in
print(request)
print(response)
if(response == true)
{
// do your thing
}
print(error)
}
注意:可能需要对 bool
的响应进行类型转换以下是您提供的 link 的屏幕截图,它 returns 正确(而不是 json 对象)[注册后,我尝试使用相同的凭据登录]