【问题标题】:Append multiple data to httpbody of URLRequest将多个数据附加到 URLRequest 的 httpbody
【发布时间】:2019-08-27 08:30:58
【问题描述】:

我想将另一个字典作为参数附加到httpBodyURLRequest

请求模型:

struct RequestModel: Encodable {

    let body: Body
}

struct Body: Encodable {
    let name: String
    let score: String
    let favList: [String]
}

API 请求:

do {
            var urlRequest = URLRequest(url: resourceURL)
            urlRequest.httpMethod = kHTTPMethodPOST
            urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
            urlRequest.httpBody = try JSONEncoder().encode(self.requestModel)

            let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, error in

                guard let httpResponse = response as? HTTPURLResponse,
                    httpResponse.statusCode == 200,
                    let jsonData = data else {
                        completion(.failure(.responseError))
                        return
                }


            }
            dataTask.resume()

        } catch {
         completion(.failure(.unknownError))
        }

另一个字典:airports

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

试图将 airports 字典参数附加到 URLRequest 但无法附加。

感谢您的帮助和建议!

谢谢

【问题讨论】:

  • 您要发送的 JSON 是什么?
  • 无关,但URLRequest → NSURLRequest → NSMutableURLRequest → URLRequest 舞蹈毫无意义。 URLRequest 是可变的,声明为 variable。而setProperty(true, forKey: ""的目的是什么?
  • 最初,我使用 URLRequest 但我们无法附加数据,因此进行了此转换。顺便说一句,我用 URLRequest 更新了。如果您知道解决方案,请提出建议!

标签: ios swift nsurlrequest


【解决方案1】:

如果您必须将 airports 字典附加到请求正文中,您可能希望将其包含在请求模型本身中。

我建议更新您的RequestModel 并改成Encodable

并将您的 airports 字典包含在您的 RequestModel

类似的东西

struct RequestModel: Encodable {

    let body: Body
    let airportsDict: [String:String]
}

struct Body: Encodable {
    let name: String
    let score: String
    let favList: [String]
}

这样您的httpBody 将拥有您想要传递的所有数据。

希望对你有帮助

【讨论】:

    【解决方案2】:

    POST JSON 的常用语法是

    do { 
        var urlRequest = URLRequest(url: resourceURL)
        urlRequest.httpMethod = "POST"
        let postData = try JSONEncoder().encode(self.requestModel)
        urlRequest.httpBody = postData
        urlRequest.setValue("\(postData.count)", forHTTPHeaderField:"Content-Length")
        urlRequest.setValue("application/json", forHTTPHeaderField:"Accept")
        urlRequest.setValue("application/json", forHTTPHeaderField:"Content-Type")
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      相关资源
      最近更新 更多