当键或值有特殊字符时,如何在objective-c中添加http POST值?

时间:2011-03-03 22:58:47

标签: objective-c http

我正在尝试使用包含$ char的密钥进行http POST,并想知道我是否正确提交

这是httpfox(RAW)中的http POST

&安培; __ EVENTTARGET = ctl00%24ContentPlaceHolder1%24btnSearch

这里是普通的txt格式(注意$ chars)

ctl00 $ $ ContentPlaceHolder1 btnSearch

但在我的字符串中,我无法获得有效的帖子做这样的事情

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 ...

1 个答案:

答案 0 :(得分:1)

看起来你需要对theBodyString进行URL编码。尝试:

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

或(回应评论)

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