5

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?

Caleb
  • 124,013
  • 19
  • 183
  • 272

2 Answers2

1

Am I missing something, or do I need to construct the request myself by combining the headers, body, etc?

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:

for (NSString *h in headers) {
    [renderedRequest appendFormat:@"%@: %@\r\n", h, [headers objectForKey:h]];
}
Caleb
  • 124,013
  • 19
  • 183
  • 272
1

According your last question:

  1. Check cookiesCenter.
  2. Check credentialsStorage.
  3. Log all headers for example on the first urlConnection's delegate method didReceiveResponse:.
  4. Make this connection with local webservice and try to catch all headers, params, etc.

Also, the most simple way, is making request yourself.

  • Thanks for your answer. I'd love to know which question you're thinking of -- I haven't asked anything like this here before, but perhaps the question you remember will help. At any rate, I should have been more specific: what I'm trying to do is to get the request *in code*. It seems like NSURLConnection might have a method like `-requestDataFromURLRequest:`. The URL loading system knows how to construct the raw request data. I want to get it to do that for me and just hand me back the request data instead of connecting and sending it. – Caleb Feb 01 '12 at 21:03
  • in this case try to use CFStream, and make request with then. You will be able to see all data in writeStream. – Serg Shiyan Feb 14 '12 at 10:22