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

前端 未结 2 427
一个人的身影
一个人的身影 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.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)")
    
        }
    
        ...
    }
    

提交回复
热议问题