这是一个快速的4个示例代码,它们使用SOAP服务格式执行API调用。
func callSOAPWSToGetData() {
let strSOAPMessage =
"<?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/\">" +
"<soap:Body>" +
"<CelsiusToFahrenheit xmlns=\"http://www.yourapi.com/webservices/\">" +
"<Celsius>50</Celsius>" +
"</CelsiusToFahrenheit>" +
"</soap:Body>" +
"</soap:Envelope>"
guard let url = URL.init(string: "http://www.example.org") else {
return
}
var request = URLRequest.init(url: url)
let length = (strSOAPMessage as NSString).length
request.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("http://www.yourapi.com/webservices/CelsiusToFahrenheit", forHTTPHeaderField: "SOAPAction")
request.addValue(String(length), forHTTPHeaderField: "Content-Length")
request.httpMethod = "POST"
request.httpBody = strSOAPMessage.data(using: .utf8)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /todos/1")
print(error ?? "")
return
}
print(responseData)
let strData = String.init(data: responseData, encoding: .utf8)
print(strData ?? "")
}
task.resume()
}