基于Swift的iOS应用程序开发:使用NSMutableURLRequest向服务器发送请求
来源:互联网 发布:汤臣倍健 鱼油 知乎 编辑:程序博客网 时间:2024/05/29 15:30
先定义好你需要发送请求的地址,以及参数:
var urlStr:String = “这是你的服务器请求地址”var requestXml:String = “这里是你的请求参数”
使用NSURL类来创建服务器地址对象:
let url:NSURL = NSURL(string:urlStr)!
创建NSMutableURLRequest对象:
let request : NSMutableURLRequest = NSMutableURLRequest(URL: url)
设置请求方式:
request.HTTPMethod = "POST"
传递请求参数:
request.httpBody = requestXml.data(using: String.Encoding.utf8)
编写一个用于处理响应的回调方法,这个方法的入参和返回类型是固定的:
func checkItemListCallback(response:URLResponse?,data:Data?,error:Error?) -> Void{ if error != nil{ print(error) } else { let responseXml = String.init(data:data!,encoding:String.Encoding.utf8) print("获得响应数据:") print(responseXml) }}
使用NSURLConnection发送请求,并设置响应回调方法:
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main, completionHandler:completionHandler)
以上就完成了所有的发送请求的步骤。下面是一个完整的封装好的方法,需要注意的是最后一个入参需要传入一个用于处理响应数据的回调方法:
func requestToServerByPost(_ postData:String,webserviceUrl:String,completionHandler:@escaping (_ response:URLResponse?,_ data:Data?,_ error:Error?) -> Void){ print("url:"+webserviceUrl) print("参数:"+postData) let url:URL = URL(string:webserviceUrl)! let request:NSMutableURLRequest = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.httpBody = postData.data(using: String.Encoding.utf8) NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main, completionHandler:completionHandler)}
以上的例子全部都是基于post方式的,如果是get方式的话,会更简单:
func requestToServerByGet(_ webserviceUrl:String,completionHandler:@escaping (_ response:URLResponse?,_ data:Data?,_ error:Error?) -> Void){ print("url:"+webserviceUrl) let url:URL = URL(string:webserviceUrl)! let request:URLRequest = URLRequest(url:url) NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler:completionHandler)}
阅读全文
0 0
- 基于Swift的iOS应用程序开发:使用NSMutableURLRequest向服务器发送请求
- 基于Swift的iOS应用程序开发:使用URLSession向服务器发送请求
- Android开发之使用Get方法向服务器发送请求
- 【ios开发学习】【swift】Xcode7 使用NSURLSession发送HTTP请求的问题
- 基于Swift的iOS应用程序开发:使用xcode进行iOS应用程序开发时,各种Launch Image尺寸清单
- 使用XMLHttpRequest对象向服务器发送简单的请求
- 基于Swift的iOS应用程序开发:使用NSUserDefaults存储本地数据
- 基于Swift的iOS应用程序开发:使用表格显示并控制数据(一):显示数据
- 基于Swift的iOS应用程序开发:使用UIImagePickerController调取摄像头进行拍照
- 基于Swift的iOS应用程序开发:使用UIImagePickerController从相册选择图片
- 向服务器发送请求
- 基于Swift的iOS应用程序开发:“属性观察器”简介
- iOS网络开发基础--向服务器发送数据的方式
- iOS开发-post请求向服务器发送json格式数据(数组或字典)
- iOS开发-post请求向服务器发送json格式数据(数组或字典)
- [iOS swift]Get方式向服务器请求数据
- 基于Qt的SocketIO客户端实现 【二】向服务器发送请求
- 基于Swift的iOS应用程序开发:使用表格显示并控制数据(四):使用UIRefreshController实现下拉刷新
- Hibernate学习之---映射组件属性
- bayes python 源代码
- 473. Matchsticks to Square
- Microsoft.AspNet.Identity 剖析(一)—— 初识 Identity
- 居中(整理)
- 基于Swift的iOS应用程序开发:使用NSMutableURLRequest向服务器发送请求
- 用Python爬取用户虾米音乐的歌单
- 光头李
- Java SE 6.0新特性体验(上篇)
- [JS]小数部分处理
- .hex 文件详解 stm32(stm32深入理解机器码)
- C#中为啥会有大小写两种类型,比如string和String
- 智能指针之make_unique与make_shared
- React-native 踩的坑