代码之家  ›  专栏  ›  技术社区  ›  user1046037

urlrequest equality不包括httpbody

  •  1
  • user1046037  · 技术社区  · 6 年前

    概述

    有2个 URLRequest 一,用 httpBody 一个没有 HTTP主体 .
    然而,当比较时,它显示两者都是相等的。

    问题

    这是预期行为还是我遗漏了什么?

    代码

    let url = URL(string: "www.somevalidURL.com")!
    
    var r1 = URLRequest(url: url)
    r1.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")
    r1.httpBody = makeBody(withParameters: ["email" : "a@b.com"])
    
    var r2 = URLRequest(url: url)
    r2.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")
    
    if r1 == r2 {
        print("requests are equal")
    }
    else {
        print("requests are not equal")
    }
    
    if r1.httpBody == r2.httpBody {
        print("body is equal")
    }
    else {
        print("body is not equal")
    }
    
    func makeBody(withParameters bodyParameters: [String : Any]?) -> Data? {
        guard let bodyParameters = bodyParameters,
            !bodyParameters.isEmpty else {
                return nil
        }
        let body : Data?
        do {
            body = try JSONSerialization.data(withJSONObject: bodyParameters,
                                              options: .prettyPrinted)
        }
        catch {
            print("Error in creating Web Service Body = \(error)")
            body = nil
        }
        return body
    }
    

    产量

    requests are equal
    body is not equal
    

    XCODE 10
    Swift版本:4.2

    1 回复  |  直到 6 年前
        1
  •  4
  •   Martin R    6 年前

    URLRequest 是基础型的快速覆盖型 NSURLRequest 这样 == 最终调用 isEqual() 方法 这个 NSURL请求 .

    基金会库是非苹果平台的开放源代码。 NSURLRequest.swift#L245 我们发现:

    open override func isEqual(_ object: Any?) -> Bool {
        //On macOS this fields do not determine the result:
        //allHTTPHeaderFields
        //timeoutInterval
        //httBody
        //networkServiceType
        //httpShouldUsePipelining
        guard let other = object as? NSURLRequest else { return false }
        return other === self
            || (other.url == self.url
                && other.mainDocumentURL == self.mainDocumentURL
                && other.httpMethod == self.httpMethod
                && other.cachePolicy == self.cachePolicy
                && other.httpBodyStream == self.httpBodyStream
                && other.allowsCellularAccess == self.allowsCellularAccess
                && other.httpShouldHandleCookies == self.httpShouldHandleCookies)
    

    所以这似乎是有意的。