如何从 NSURLRequest 获取完整的请求?
有什么方法可以获取当 NSURLConnection 发送 NSURLRequest 时将发送的实际数据吗?现在我主要感兴趣的是查看 HTTP 和 HTTPS 请求,但由于 NSURLRequest 适用于许多协议,因此似乎应该有一种通用方法来查看任何类型请求的相应数据。
我是否遗漏了某些内容,或者我是否需要通过组合标头、正文等来自己构建请求?
需要明确的是,我想以编程方式执行此操作,而不是通过观察服务器端显示的内容。
更新:此时,我已经编写了使用 NSURLRequest 中的数据有效构造请求的代码,因此我不是在问如何去做。但是,我仍然想知道是否有办法访问 URL 加载系统生成的请求流。换句话说,如果 NSURLConnection 发送我的 NSURLRequest,我可以访问将发送的确切字节吗?
Is there any way to get the actual data that will be sent when a NSURLConnection sends a NSURLRequest? Right now I'm mainly interested in looking at HTTP and HTTPS requests, but since NSURLRequest works for many protocols, it seems like there ought to be a general way to see the corresponding data for any type of request.
Am I missing something, or do I need to construct the request myself by combining the headers, body, etc?
Just to be clear, I'd like to do this programmatically, not by watching what shows up at the server end.
Update: At this point I've written code that effectively constructs a request using the data in a NSURLRequest, so I'm not asking how to go about that. However, I'd still like to know if there's a way to access the request stream that the URL loading system would generate. In other words, can I get access to the exact bytes that would be sent if a NSURLConnection were to send my NSURLRequest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据你的最后一个问题:
didReceiveResponse:
上记录所有标头。此外,最简单的方法是自己发出请求。
According your last question:
didReceiveResponse:
.Also, the most simple way, is making request yourself.
事实证明这正是我需要做的,而且是有道理的。协议处理程序(NSURLProtocol 子类),而不是 NSURLRequest,知道如何格式化其特定协议的请求。幸运的是,将 NSURLRequest 实例呈现为有效的 HTTP 请求非常容易。您可以从请求中获取方法(GET、POST 等)、请求的资源和主机,还可以使用
-allHTTPHeaderFields
方法获取所有 HTTP 标头,该方法返回一个字典。然后,您可以循环字典中的键并向请求添加行,例如:It turns out that this is exactly what I needed to do, and it makes sense. It's the protocol handler (NSURLProtocol subclass), not NSURLRequest, that knows how to format the request for its particular protocol. Luckily, it's very easy to render an instance of NSURLRequest into a valid HTTP request. You can get the method (GET, POST, etc.), requested resource, and host from the request, and you can also get all the HTTP headers using the
-allHTTPHeaderFields
method, which returns a dictionary. You can then loop over the keys in the dictionary and add lines to the request like: