如何使用带有委托方法的 NSURLSession 连接到 Web 服务? [英] How to connect to a web service using NSURLSession with Delegate methods?

查看:71
本文介绍了如何使用带有委托方法的 NSURLSession 连接到 Web 服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接到 iOS 中的 Web 服务,但遇到了很多问题.我在这里找到了一个练习网络服务 - http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit

I am taking a stab at connecting to web services in iOS and I am running into a lot of problems. I found a practice web service here - http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit

到目前为止我已经写出了这段代码

I have written this code out so far

    let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
    "<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/\">\n"
    "<soap:Body>\n"
    "<CelsiusToFahrenheit xmlns=\"http://www.w3schools.com/webservices/\">\n"
    "<Celsius>50</Celsius>\n"
    "</CelsiusToFahrenheit>\n"
    "</soap:Body>\n"
    "</soap:Envelope>\n"

    let url = NSURL(string: "http://w3schools.com/webservices/tempconvert.asmx")!

    var request = NSMutableURLRequest(URL: url)

    let messageLength = "\(soapMessage.utf16Count)"
    NSLog("\(messageLength)")
    request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.addValue("http://www.w3schools.com/webservices/CelsiusToFahrenheit", forHTTPHeaderField: "SOAPAction")
    request.addValue(messageLength, forHTTPHeaderField: "Content-Length")
    request.HTTPMethod = "POST"
    request.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

    var urlSession: NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())

它可以连接,但我的响应以 text/html 而不是 text/xml 的形式返回.我的问题是为什么它返回错误?我还使用 NSURLSessionDataTask 还是 NSURLSessionDownloadTask?

It works to connect but my response comes back as as text/html and not text/xml. My question is why is it returning incorrectly? Also do I use a NSURLSessionDataTask or NSURLSessionDownloadTask?

推荐答案

对于你的情况,我认为它是 NSURLSessionDataTask.基于此站点:http://www.kaleidosblog.com/nsurlsession-in-swift-get-and-post-data

for your case, i think its NSURLSessionDataTask. based on this site: http://www.kaleidosblog.com/nsurlsession-in-swift-get-and-post-data

这篇关于如何使用带有委托方法的 NSURLSession 连接到 Web 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆