Why is the HTTPBody of a request inside an NSURLProtocol Subclass always nil?

前端 未结 2 398
一个人的身影
一个人的身影 2021-01-13 14:59

I have my NSURLProtocol MyGreatProtocol. I add it to the URL Loading system,

NSURLProtocol.registerClass(MyGreatProtocol)

I th

相关标签:
2条回答
  • 2021-01-13 15:26

    Here's a sample code for reading the httpBody:

    Swift 5

    extension URLRequest {
    
        func bodySteamAsJSON() -> Any? {
    
            guard let bodyStream = self.httpBodyStream else { return nil }
    
            bodyStream.open()
    
            // Will read 16 chars per iteration. Can use bigger buffer if needed
            let bufferSize: Int = 16
    
            let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
    
            var dat = Data()
    
            while bodyStream.hasBytesAvailable {
    
                let readDat = bodyStream.read(buffer, maxLength: bufferSize)
                dat.append(buffer, count: readDat)
            }
    
            buffer.deallocate()
    
            bodyStream.close()
    
            do {
                return try JSONSerialization.jsonObject(with: dat, options: JSONSerialization.ReadingOptions.allowFragments)
            } catch {
    
                print(error.localizedDescription)
    
                return nil
            }
        }
    }
    

    Then, in URLProtocol:

    override func startLoading() {
    
        ...
    
        if let jsonBody = self.request.bodySteamAsJSON() {
    
            print("JSON \(jsonBody)")
    
        }
    
        ...
    }
    
    0 讨论(0)
  • 2021-01-13 15:41

    IIRC, body data objects get transparently converted into streaming-style bodies by the URL loading system before they reach you. If you need to read the data:

    • Open the HTTPBodyStream object
    • Read the body data from it

    There is one caveat: the stream may not be rewindable, so don't pass that request object on to any other code that would need to access the body afterwards. Unfortunately, there is no mechanism for requesting a new body stream, either (see the README file from the CustomHTTPProtocol sample code project on Apple's website for other limitations).

    0 讨论(0)
提交回复
热议问题