为什么NSURLProtocol子类中的请求的HTTPBody始终为零?

我有我的NSURLProtocol MyGreatProtocol 。 我将它添加到URL加载系统,

 NSURLProtocol.registerClass(MyGreatProtocol) 

然后我在networking会话期间开始接收MyGreatProtocol内部的事件。

假设我在注册我的协议后创build会话,

 let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: NSURL(string:"http://example.com")!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 2.0) //arbitrary 404 request.HTTPBody = ([1, 3, 3, 7] as [UInt8]).toNSData print("body data: \(request.HTTPBody)") //prints `Optional(<01030307>)` request.HTTPMethod = "POST" session.dataTaskWithRequest(request) { (data, response, err) in print("data: \(data)\nresponse: \(response)\nerror\(err)") }.resume() 

我希望请求的HTTP主体1/3/3/7存在于MyGreatProtocol ,而不是。

MyGreatProtocol里面,我重写了下面的方法。

 override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest { print(request.HTTPBody) //prints nil return request } override class func canInitWithRequest(request: NSURLRequest) -> Bool { print(request.HTTPBody) //prints nil return true } override func startLoading() { print(self.request.HTTPBody) //prints nil } 

NSURLRequest的其他属性似乎保留。 URL,HTTP动词,标题等都在那里。 一些具体的身体性质仍然难以捉摸。

为什么在自定义的NSURLProtocol中没有HTTP主体?

似乎有一些类似的讨论雷达以前提交(即https://bugs.webkit.org/show_bug.cgi?id=137299 )

IIRC,身体数据对象在到达您之前通过URL加载系统透明地转换为stream风格的实体。 如果你需要读取数据:

  • 打开HTTPBodyStream对象
  • 从中读取正文数据

有一个警告:stream可能不可回滚,所以不要将该请求对象传递给任何其他需要访问主体的代码。 不幸的是,还没有请求新的主体stream的机制(请参阅Apple网站上CustomHTTPProtocol示例代码项目的README文件以了解其他限制)。