制作URLRequest时Swift随机400错误

时间:2018-05-27 21:56:04

标签: swift nsurlrequest

我正在尝试与API进行交互。该服务通常可以工作并返回200响应,但偶尔会响应400错误,并且调试描述中只有空白标题。我已经做了一个递归函数来尝试传递相同的请求,我最终在1-3次尝试中得到200响应,即使我正在做同样的请求。我通过Postman和PHP提出请求,在与API交互时从未遇到过这个问题。只有在Swift中发出请求时

    func process(table: String, path: String, objectId: String? = nil, pendingWriteId: String? = nil, method: ApiMethod, processData: [String: Any] = [:], filter: [String: Any] = [:], initializing: Bool = false, remove: Bool = false, completion: @escaping (Error?, JSON) -> Void) {
                var timestamp: Int = Int(Date().timeIntervalSince1970)

                let session = URLSession.shared
                        let url : String = "\(apiURL)\(path)"

                    var params: [String:Any] = [:]

                    if method != .GET {
                        params["data"] = processData
                        params["filter"] = filter
                        params["timestamp"] = timestamp
                    }

                    if method == .DELETE {
                        params["remove"] = remove
                    }

                    let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
                    request.httpMethod = method.rawValue

                    if let token = auth.authToken {
                        request.setValue(token, forHTTPHeaderField: "token")
                    }

                    print(url)
                    self.sendRequest(session: session, request: request, params: params, pendingWriteId: pendingWriteId, initializing: initializing) { (error, json) in
                        completion(error, json)
                        return
                    }
        }

        func sendRequest(session: URLSession, request: NSMutableURLRequest, params: [String:Any], pendingWriteId: String?, initializing: Bool, completion: @escaping (Error?, JSON) -> Void) {
            do{
                request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions.prettyPrinted])

                _ = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
                    DispatchQueue.main.async {
                        if let response = response {
                            let nsHTTPResponse = response as! HTTPURLResponse
                            let statusCode = nsHTTPResponse.statusCode
                            if statusCode == 200 {
                                if let d = data {
                                    do {
                                        let json = try JSON(data: d)
                                        print(json)
                                        completion(error, json)
                                        return
                                    } catch {
                                        completion(error, JSON())
                                        return
                                    }
                                }
                            } else {
                                print ("\(request.url) status code = \(statusCode)")
                                print(nsHTTPResponse.description)
                                self.sendRequest(session: session, request: request, params: params, pendingWriteId: pendingWriteId, initializing: initializing) { (error, json) in
                                    completion(error, json)
                                    return
                                }
                            }
                        } else {
                            completion(error, JSON())
                            return
                        }
                    }
                }).resume()
            }catch _ {
                print ("Oops something happened")
                completion(ApiError.willNotResolve, JSON())
                return
            }
        }

1 个答案:

答案 0 :(得分:2)

经过近一天的努力解决这个问题后,我在几分钟的时间内解决了这个问题。问题是我试图JSON编码一个空参数集。我改变了

request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions.prettyPrinted])

if params.count > 0 {
       request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions.prettyPrinted])
}

现在按预期工作