在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
/** 所有网络请求,统一使用异步请求!
在今后的开发中,如果使用简单的get/head请求,可以用NSURLConnction异步方法 GET查/POST增/PUT改/DELETE删/HEAD
GET 1> URL 2> NSURLRequest 3> NSURLConnction 异步
POST 1> URL 2> NSMutableURLRequest .httpMethod = @"POST"; str 从 firebug直接粘贴,或者自己写 变量名1=数值1&变量名2=数值2
.httpData = [str dataUsingEncoding:NSUTF8StringEncoding]; 3> NSURLConnction 异步
*/ overridefunc viewDidLoad() { super.viewDidLoad() self.postLogon() } func postLogon(){ var path ="http://xxxxxxxx.com" var params:NSMutableDictionary = NSMutableDictionary() params["mobile_phone"] ="1xxxxxxxxx5" params["password"] ="123456"
var headparams:NSMutableDictionary = NSMutableDictionary() headparams["X-xxxx-App-Token"] = "xxxxxx-xxx-xxxx-xxxx-xxxxxxxxxx" // 1. URL var url:NSURL = NSURL(string: path)!
// 2. 请求(可以改的请求) var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) // ? POST // 默认就是GET请求 request.HTTPMethod ="POST"
// ? 数据体 var jsonData:NSData? =nil do { jsonData = tryNSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted) } catch {
} // 将字符串转换成数据 request.HTTPBody = jsonData
request.setValue("xxxxxx-xxx-xxxx-xxxx-xxxxxxxxxx", forHTTPHeaderField:"X-xxxx-App-Token") NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue()) { (res, data, error)in
let str =NSString(data: data!, encoding:NSUTF8StringEncoding) print(str)
} }
//#pragma mark - POST登录 func posttoken() {
var path ="http://xxxxxxxxx/app/token/request_token" let params:NSMutableDictionary = NSMutableDictionary() params["app_id"] = "000000000000000000000" params["app_secret"] ="000000000000000000000" params["mobile_id"] ="000000000000000000000"
// 1. URL var url:NSURL = NSURL(string: path)!
// 2. 请求(可以改的请求) var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) // ? POST // 默认就是GET请求 request.HTTPMethod ="POST" // ? 数据体 var jsonData:NSData? =nil do { jsonData = tryNSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted) } catch {
} // 将字符串转换成数据 request.HTTPBody = jsonData
// 3. 连接,异步 NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue()) { (res, data, error)in if(error ==nil){ var dict:NSDictionary? =nil do { dict = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.init(rawValue:0)) as!NSDictionary } catch {
} //将str转换为字典 //{"data": //{"token":"2e2f6b61-8101-49cf-b7dd-7cfea6f0c499","expire_at":1462885914} // } //取data的值 var data:NSDictionary = dict!["data"] as! NSDictionary //取token的值 var token = data["token"]as! String print(token)
} }
} } |
请发表评论