我在POST查询中遇到了一些问题;请帮忙。它总是向我发送400 Bad请求响应。我已经彻底检查了一切,但它只是不起作用。请帮忙。
代码是 -
struct RegisterService {
var authToken: String = ""
var baseURL = NSURL(string: "")
func getToken(name: String, email: String, password: String, cfmpassword: String, completion: (AuthToken? -> Void)) {
let request = NSMutableURLRequest(URL: baseURL!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let params = ["accept":"on", "cfmpassword":"\(cfmpassword)",
"email":"\(email)", "name":"\(name)", "password":"\(password)"]
as Dictionary<String, AnyObject>
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
} catch {
print("Request Unsuccessful")
}
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print(request)
print(data)
print(response)
if let httpResponse = response as? NSHTTPURLResponse {
switch httpResponse.statusCode {
case 200:
// 2. Create JSON object with data
do {
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject]
let authToken = AuthToken(tokenDictionary: jsonDictionary!)
completion(authToken)
} catch {
print("Fetch failed: \((error as NSError).localizedDescription)")
}
default:
print("GET request not successful. HTTP status code: \(httpResponse.statusCode)")
NSOperationQueue.mainQueue().addOperationWithBlock {
completion(nil)
}
}
} else {
print("Error: Not a valid HTTP response")
NSOperationQueue.mainQueue().addOperationWithBlock {
completion(nil)
}
}
})
task.resume()
}
}
答案 0 :(得分:0)
let params = ["accept":"on", "cfmpassword":"\(cfmpassword)", "email":"\(email)", "name":"\(name)", "password":"\(password)"] as Dictionary<String, AnyObject>
let boundary:String = "---------------------------14737809831466499882746641449"
let body:NSMutableData = NSMutableData()
if params != nil
{
for (key, value) in params!
{
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
body.appendString("--\(boundary)--\r\n")
request.setValue("\(body.length)", forHTTPHeaderField:"Content-Length")
request.HTTPBody = body