1

Is there a convenient way to view or print a NSMutableURLRequest as a raw HTTP request -- i.e. how it gets sent over the wire? Perhaps when the request is actually made? I'm specifically not trying to extract specific components of the request and manually compose them together. FWIW I'm loading it in a webview with WKWebView.loadRequest(r).

By raw request, I mean as it is sent over the wire -- something like:

POST /target/command HTTP/1.0
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508
Content-Type: application/json
Content-Length: 38914
Custom-Header: custom-value

{"param": "value"}

The reason I'm asking is because my server seems to receive an empty request body for a particular request, while it receives request bodies on others. Would be very useful if I could debug this like I debug on my server -- by printing the raw request. I understand I could use proxy tools like Charles, but I'm hoping there's a more convenient answer.

2 Answers2

0

I generally just print out all outgoing requests as a copy/pasteable cURL command with a category like this, you can probably reformat it if you don't need the functionality.

@implementation NSURLRequest (cURLRepresentation)

- (NSString *)escapeQuotesInString:(NSString *)string {
    NSParameterAssert(string.length);

    return [string stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
}

- (NSString *)cURLRepresentation {

    NSMutableString *curlString = [NSMutableString stringWithFormat:@"-------\ncurl -k -X %@ --dump-header -", self.HTTPMethod];

    for (NSString *key in self.allHTTPHeaderFields.allKeys) {

        NSString *headerKey = [self escapeQuotesInString: key];
        NSString *headerValue = [self escapeQuotesInString: self.allHTTPHeaderFields[key] ];

        [curlString appendFormat:@" -H \"%@: %@\"", headerKey, headerValue];
    }

    NSString *bodyDataString = [[NSString alloc] initWithData:self.HTTPBody encoding:NSUTF8StringEncoding];
    if (bodyDataString.length) {

        bodyDataString = [self escapeQuotesInString: bodyDataString];
        [curlString appendFormat:@" -d \"%@\"", bodyDataString];
    }

    [curlString appendFormat:@" \"%@\"", self.URL.absoluteString];
    [curlString appendFormat:@"\n-------"];

    return curlString;
}

@end
0

Used RequestBin (requestb.in) instead to make sure I wasn't going crazy... Turns out there's a bug in WKWebView.loadRequest(r) where r.HTTPBody will not get passed in the request body even when non-nil. Sigh.