Toran Billups
Toran Billups

Reputation: 27407

How to add a http POST value in objective-c when the key or value has special chars?

I'm attempting to do an http POST that has a key containing a $ char and wanted to know if I'm submitting it correctly

here is the http POST in httpfox (RAW)

&__EVENTTARGET=ctl00%24ContentPlaceHolder1%24btnSearch

here it is the plain txt format (notice the $ chars)

ctl00$ContentPlaceHolder1$btnSearch

but in my string I couldn't get a valid post doing something like this

NSURL *url = [NSURL URLWithString:@"https://www.localhost.com/someurl.aspx"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    NSString* theBodyString = [NSString stringWithFormat:@"__EVENTTARGET=ctl00$ContentPlaceHolder1$btnSearch"];
    NSData *requestData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPMethod:@"POST"];
    //other request details ...

Upvotes: 0

Views: 388

Answers (1)

Sig
Sig

Reputation: 5188

Looks like you need to URL encode theBodyString. Try:

NSString* theBodyString = [NSString stringWithFormat:@"__EVENTTARGET=ctl00$ContentPlaceHolder1$btnSearch"];
NSString* escapedUrlString = [theBodyString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
NSData *requestData = [escapedUrlString dataUsingEncoding:NSUTF8StringEncoding];

or (in response to the comment)

NSString* theBodyString = @"2010 19:32";
NSString* escapedUrlString =  (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)theBodyString, (CFStringRef)@" ", (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
escapedUrlString = [escapedUrlString stringByReplacingOccurrencesOfString:@" " withString:@"+"];

Upvotes: 1

Related Questions