我想向我的服务器发帖子请求。但当我得到响应时,服务器说我发错了数据。我提出请求的代码是:
let urlAddress = Constants.API_DOMEN + Constants.SOC_LOGIN_ENDING
let request = NSMutableURLRequest(URL : NSURL(string: urlAddress)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let params = [Constants.NAME : name,
Constants.EMAIL: email,
Constants.PROVIDER: provider,
Constants.UID: userId,
Constants.PHONE_NUMBER: phoneNumber,
Constants.AVATAR: photoURL,
Constants.TYPE: "3",
Constants.KEY: getMD5Hash(userId, provider: provider)]
as Dictionary<String, String>
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request){ data, response, error in
....
但是当我收到回复时
...
let task = session.dataTaskWithRequest(request){ data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
.....
我明白了:
dataString NSString? "{\"head\": {\"errcode\": 400}, \"postdata\":
{\"oe\": [\"57AE2750\\\",\\\"phone\\\":\\\"\\\",
\\\"name\\\":\\\"\\u0418\\u043b\\u044c\\u044f \\u041c\\u044f\\u0441\\u043e\\u0435\\u0434\\u043e\\u0432\\\",
\\\"provider\\\":\\\"facebook\\\",
\\\"uid\\\":\\\"236653050055667\\\",
\\\"type\\\":\\\"3\\\",
\\\"key\\\":\\\"b182111b0cf5d2b0e652675eac544490\\\"}\"], \"{\\\"email\\\":\\\"\\\",\\\"avatar\\\":
\\\"https:\\\\/\\\\/scontent.xx.fbcdn.net\\\\/hprofile-xfa1\\\\/v\\\\/t1.0-1\\\\/s200x200\\\\/10354686_10150004552801856_220367501106153455_n.jpg?oh\": [\"e809266ec7a9e37c304ff6ec183b735b\"]},
\"error\": {\"name\": 401, \"type\": 401,
\"uid\": 401, \"key\": 401, \"provider\": 401}}"
1)在字段名称中,我得到了错误的符号。我认为这里的编码有问题。
2)IOS在每个引用中添加符号“\”。但我无法理解为什么。
感谢任何帮助!
答案 0 :(得分:0)
我找到了解决方案。发布帖子请求的正确方法如下所示。我添加了完整的功能:
class func socialSignIn(name : String!, email: String!, provider: String!, userId: String!, photoURL: String!, phoneNumber: String!){
var globalSuccess:Bool = false
let urlAddress = Constants.API_DOMEN + Constants.SOC_LOGIN_ENDING
let request = NSMutableURLRequest(URL : NSURL(string: urlAddress)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var postString = Constants.NAME + "=" + name + "&";
postString = postString + Constants.EMAIL + "=" + email + "&";
postString = postString + Constants.PROVIDER + "=" + provider + "&";
postString = postString + Constants.UID + "=" + userId + "&";
postString = postString + Constants.PHONE_NUMBER + "=" + phoneNumber + "&";
postString = postString + Constants.AVATAR + "=" + photoURL + "&";
postString = postString + Constants.TYPE + "=" + "3" + "&";
postString = postString + Constants.KEY + "=" + getMD5Hash(userId, provider: provider);
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request){ data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
//get user cookies
let sessionId = getSessionId(response!)
PreferencesHelper.setAuthToken(sessionId)
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary{
let success = json.objectForKey("head")?.objectForKey("errcode") as? Int
if success == Constants.SUCCESS {
globalSuccess = true
}
print("Success: \(success)")
}else{
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) // No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError{
print(parseError) // Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
NSNotificationCenter.defaultCenter().postNotificationName(ViewController.notificationResult, object: nil, userInfo:[Constants.SUCCESS:globalSuccess ])
}
task.resume()
}
获取会话ID的函数如下所示:
class func getSessionId(response: NSObject)->String{
if let httpResponse = response as? NSHTTPURLResponse{
if let headers = httpResponse.allHeaderFields as? [String:String], url = httpResponse.URL{
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headers, forURL: url)
for cookie in cookies{
var cookieProperties = [String: AnyObject]()
cookieProperties[NSHTTPCookieName] = cookie.name
if (cookie.name == "sessionid"){
return cookie.value
}
}
}
}
return ""
}