先定义好你需要发送请求的地址,以及参数:
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)
}