swift - 快速发送 get/put/post

标签 swift xml post get put

我可以轻松发出 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-Typeapplication/x-www-form-urlencoded 。)

但是,在另一个应用程序中我需要 POST 一段 XML。经过多次尝试并出现许多错误后,我使用的方法是: 设置 header Content-Typetext/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数据,您可以在PUTPOST中执行此操作

不必确定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/

相关文章:

swift - 如何在搜索栏swift的 TableView 结果中加载数据

ios - 如何在TableView中的CollectionView中获取图像的索引路径?

ios - App 在发布时崩溃,被 Apple 拒绝

c++ - Xerces-C:在 HTML 中解析 Javascript

Android - 图层列表椭圆形有额外的内线

Django - 使用 request.GET 和 request.POST 之间的区别

ios - 仅当我将手机置于横向模式时才会加载表格 View

android - Android 上 kml 的 simpleframework xml 和 @ElementList 的问题

python - POST 请求文件 python-requests

python - 使用 Python 的 BaseHTTPServer 从 POST 请求中获取文件