使用Swift创建一个SOAP的请求

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值