swift 网络请求 Get、Post HttpRequest For Swift language (iOS )
来源:互联网 发布:战争程序员白濑 编辑:程序博客网 时间:2024/06/02 05:50
1.Xcode7后注意HTTP请求的处理: Add "NSAppTransportSecurity (NSAllowsArbitraryLoads Boolean YES)" in info.plist
2.Get:
let url_origin = "http://..."
let url_percent = url_origin.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url:NSURL =NSURL(url_percent!)!
let requets:NSURLRequest =NSURLRequest(URL: url)
let configuration:NSURLSessionConfiguration =NSURLSessionConfiguration.defaultSessionConfiguration()
let session:NSURLSession =NSURLSession(configuration: configuration)
let task:NSURLSessionDataTask = session.dataTaskWithRequest(requets, completionHandler: {
(data:NSData?,response:NSURLResponse?,error:NSError?)->Voidin
if error == nil{
do{
let responseData:NSDictionary =try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments) as! NSDictionary
print(responseData)
//如果responseData是Json格式,可以通过 responseData["key的名字"] 来获取相应的value值 if the form of the responseData is "Json" , we can get the value through responseData["the name of key"]
}catch{
}
}
})
task.resume() //start task
3.Post:
let request =NSMutableURLRequest(URL:NSURL(string:"http://...?")!)
request.HTTPMethod ="POST"
let postStr = "key=value&key2=value2&...&keyN=valueN"
request.HTTPBody = postStr.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
(data:NSData?,response:NSURLResponse?,error:NSError?)->Voidin
if error == nil{
do{
let responseString =NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Post result \(responseString)")
//根据返回结果进行解析做进一步处理 further processing
}catch{
print("error")
}
}
})
task.resume()
- swift 网络请求 Get、Post HttpRequest For Swift language (iOS )
- 【Swift】 GET&POST请求 网络缓存的简单处理
- HTTPRequest 网络请求之get请求和post请求
- ios-Swift中封装AFN中的GET和POST请求
- swift开发网络篇—利用NSURLConnection GET请求和POST请求
- swift开发网络篇 - post 请求
- swift开发网络篇—利用NSURLSession 发送GET和POST请求
- Swift - 原生GET&POST请求的用法
- Swift的学习(NSURLSession发送get、post请求)
- iOS-网络-同步请求、异步请求、GET请求、POST请求
- ios网络请求 get——post
- iOS 发送GET和POST网络请求
- iOS——GET POST 网络请求
- iOS NSURLSession网络请求(get/post/下载)
- iOS网络请求GET&POST,同步&异步
- Swift之网络请求
- swift 网络请求 2
- Swift网络请求
- cannot convert parameter 1 from 'int' to 'int []'
- BZOJ 4269 高斯消元求线性基
- Android AA框架
- Spring - 事务
- Minimum Path Sum
- swift 网络请求 Get、Post HttpRequest For Swift language (iOS )
- 深入解读Spring Framework IoC容器(第二弹:依赖注入的方式)
- weka学习比较好的网址
- SSH框架整合
- 两种广播接受方式
- 简单的冒泡排序
- 404. Sum of Left Leaves#2(Done)
- Terrain Splatting
- 支持向量机通俗导论(理解SVM的三层境界)