Created
September 15, 2015 10:13
-
-
Save akfreas/362df824d5d311033ae0 to your computer and use it in GitHub Desktop.
NSURLRequest Create cURL Command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NSURLRequest (cURL) | |
- (NSString *)curlCommand; | |
@end | |
@implementation NSURLRequest (cURL) | |
- (NSString *)curlCommand | |
{ | |
NSString *(^stringFromDict)(NSDictionary *dict) = ^NSString*(NSDictionary *dict){ | |
NSMutableString *paramString = [NSMutableString stringWithString:@"{"]; | |
for (NSString *key in dict) { | |
NSString *param = [NSString stringWithFormat:@"\"%@\" : \"%@\", ", key, dict[key]]; | |
[paramString appendString:param]; | |
} | |
[paramString appendString:@"}"]; | |
return paramString; | |
}; | |
NSMutableString *fullParamString = [NSMutableString stringWithString:@""]; | |
if (self.HTTPBody) { | |
id data = [NSJSONSerialization JSONObjectWithData:self.HTTPBody options:0 error:nil]; | |
if ([data isKindOfClass:[NSArray class]]) { | |
[fullParamString appendString:@"[%@"]; | |
for (NSDictionary *dict in data) { | |
[fullParamString appendString:stringFromDict(dict)]; | |
} | |
[fullParamString appendString:@"]"]; | |
} else { | |
fullParamString = [stringFromDict(data) mutableCopy]; | |
} | |
} | |
NSMutableString *headerString = [NSMutableString string]; | |
for (NSString *key in [self allHTTPHeaderFields]) { | |
[headerString appendFormat:@" -H \"%@: %@\"", key, [self valueForHTTPHeaderField:key]]; | |
} | |
NSString *command = [NSString stringWithFormat:@"curl -X %@ %@ -d '%@' %@", self.HTTPMethod, headerString, fullParamString, [self.URL absoluteString]]; | |
return command; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment