我可以轻松发出 GET 请求,它会返回(按预期)解码为 myDataModel 对象的 JSON 数据:
class func getData(completionHandler: @escaping (myDataModel?, Error?) -> Void)
{
let url = "https://example.com/api/someResource?ws_key=ABC...XYZ"
if let myUrl = URL(string: url)
{
URLSession.shared.dataTask(with: myUrl)
{
(data, response, err) in
if let data = data
{
do
{
let result = try JSONDecoder().decode(myDataModel.self, from: data)
completionHandler(result, nil)
}
catch let JSONerr
{
completionHandler(nil, JSONerr)
}
}
}.resume()
}
}
这工作正常,所以 GET 没有问题。 (PS.以上已简化修改。)
同样,当我使用 key1=value1&key2=value2
等参数时,我可以发出 POST 请求,它会返回(按预期)JSON 数据。 。 (我读到默认的 POST Content-Type
是 application/x-www-form-urlencoded
。)
但是,在另一个应用程序中我需要 POST 一段 XML。经过多次尝试并出现许多错误后,我使用的方法是: 设置 header Content-Type
至text/xml; charset=utf-8
;没有参数并将 XML 作为请求正文发送。我使用了一种精炼的方法:
PostHTTP(url: "https://example.com/api/someResource?ws_key=ABC...XYZ",
parameters: nil,
headers: ["Content-Type": "text/xml; charset=utf-8", "Content-Length": "\(xml.count)"],
body: "\(xml)") { (result) in ... }
(我认为您可以确定幕后发生的事情。)
对于 POST 请求,发送一段 XML:
我需要设置 Content-Length
或者这是自动的?
我可以使用 XML 发送参数吗?
我需要什么 header (例如 Content-Type
)?
我需要什么结构(例如 xml=<?xml
...)和编码(例如 addingPercentEncoding
)?
我还需要 PUT 数据,我有类似的方法。我的尝试的响应有错误
String could not be parsed as XML, XML length: 0
对于 PUT 请求:
我需要什么 header (例如 Content-Type
)?
我需要什么结构(例如 xml=<?xml
...)和编码(例如 addingPercentEncoding
)?
由于我尝试了很多方法,因此 PUT 和 POST 的示例是理想的。
最佳答案
如果您想发送XML
数据,您可以在PUT
和POST
中执行此操作
不必确定Content-Length
但您必须添加 Content-Type
let req = NSMutableURLRequest(url: URL(string:"myUrl")!)
req.httpMethod = "POST"
req.setValue("application/xml;charset=utf-8;", forHTTPHeaderField: "Content-Type")
req.setValue("application/xml;", forHTTPHeaderField: "Accept")
var postBody = Data()
if let anEncoding = ("<?xml version='1.0' encoding='UTF-8'?>").data(using: .utf8) {
postBody.append(anEncoding)
}
if let anEncoding = "<Request>".data(using: .utf8) {
postBody.append(anEncoding)
}
if let anEncoding = "<test>\(123)</test>".data(using: .utf8) {
postBody.append(anEncoding)
}
if let anEncoding = "</Request>".data(using: .utf8) {
postBody.append(anEncoding)
}
req.httpBody = postBody
req.setValue("\(postBody.count)", forHTTPHeaderField: "Content-Length")
URLSession.shared.dataTask(with: req as URLRequest) { (data, urlreq, error) in
}
关于swift - 快速发送 get/put/post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296849/