自己稍微对请求头和请求体进行封装了下,代码如下:
import UIKit
import Alamofire
typealias SuccessBlock = (NSData)->Void
typealias FaileBlock = (NSError)->Void
class NetWorkManager: NSObject{
var webData: NSMutableData!//接受的网络数据
var currentService: String = String()//调用的服务
var currentAction: String = String()//调用服务的接口
var successBlock: SuccessBlock?//成功后的委托
var fauleBlock: FaileBlock?//失败的委托
func postRequest(service:String,action:String,paramValues:String,success:SuccessBlock){
self.successBlock = success
self.currentService = service
self.currentAction = action
let URL = getURL(service, action: action)//封装了一个方法,用于拼接URL
//toSoapMessage(action,pams)用于拼接消息体
let soapMsg:String = toSoapMessage(action, pams: paramValues)
//getMutableRequest()设置请求头的信息
let mutableURLRequest: NSMutableURLRequest = getMutableRequest(action, URL: URL, soapMsg: soapMsg)
Alamofire.request(mutableURLRequest).responseData { response in
if let successful = self.successBlock{
successful(response.data!)
}else{
//调用请求失败的委托
}
}
}
//设置请求头
func getMutableRequest(action:String,URL:NSURL,soapMsg:String)->NSMutableURLRequest{
let mutableURLRequest: NSMutableURLRequest = NSMutableURLRequest(URL:URL)
mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
let soapAction = kNameSpace+action
print("\(soapAction)")
mutableURLRequest.setValue(soapAction, forHTTPHeaderField: "SOAPAction")
mutableURLRequest.setValue("\(soapMsg.characters.count)", forHTTPHeaderField: "Content-Length")
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.HTTPBody = soapMsg.dataUsingEncoding(NSUTF8StringEncoding)
return mutableURLRequest
}
//拼接URL,“?op=”这个破玩意儿,让我写成“/”,坑死我了(在地址栏中会自动转换为“?op=”,代码不行!!!!)。
func getURL(service:String,action:String)->NSURL{
let urlStr = kURLHeader+service+"?op="+action
return NSURL(string: urlStr)!
}
//拼接请求体
//拼接地址的文件,贴图吧省事一点。。。