使用Swift创建一个SOAP的请求

来源:互联网 发布:pp助手 mac 铃声制作 编辑:程序博客网 时间:2024/05/18 00:03

Swift版本2.0
有一个小地方需要注意在成功的Return我使用了一个第三方的XML转字典的库~访问默认传回来的是NSdata,第三方库叫做XMLDictionary,需要的可以在github上搜索一下~

/**使用Post方式请求WebCommonService数据:param: PostUrl    WebCommonService地址:param: SOAPAction SOAPAction响应地址:param: SoapBody   SoapBody结构*/func SDXmlrequestPost(PostUrl:String,SOAPAction:String,SoapBody:String,Success:(results:NSDictionary) -> Void,Failure:(error:NSError?)->Void){    //创建SOAP消息    let SoapMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\(SoapBody)</soap:Envelope>"//    print(SoapMsg)    //创建一个URL请求    let Url = NSURL(string: PostUrl)    //创建请求对象    let request = NSMutableURLRequest(URL: Url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 15)    //添加请求头    request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")    request.addValue("\(SoapMsg.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))", forHTTPHeaderField: "Content-Length")    request.addValue(SOAPAction, forHTTPHeaderField: "SOAPAction")    request.HTTPMethod = "POST"    // 将SOAP消息加到请求中    request.HTTPBody = SoapMsg.dataUsingEncoding(NSUTF8StringEncoding)    let seesion = NSURLSession.sharedSession()    let dataTask = seesion.dataTaskWithRequest(request) { (data:NSData?, req:NSURLResponse?, error:NSError?) -> Void in        if error == nil{   //把XML数据转字典    return Success(results: NSDictionary(XMLData: data!))        }else{    return Failure(error: error)        }    }    //启动任务    dataTask.resume()}
0 0
原创粉丝点击