Caleb
Caleb

Reputation: 124997

How to get a complete request from a 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?

Upvotes: 5

Views: 1341

Answers (2)

Caleb
Caleb

Reputation: 124997

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]];
}

Upvotes: 1

Serg Shiyan
Serg Shiyan

Reputation: 95

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.

Upvotes: 1

Related Questions