我如何为GET请求编码url字符串?我特意遇到一个问题,我要发送的字段的值包括&符号(&),它被解释为字段之间的分隔符。
我目前正在创建我的请求如下(实际调用的代码来自Apple的MVC Networking示例,因此它可能与此问题无关,但为了完整性而包含在内)
NSString *urlString = [[NSString alloc] initWithFormat:@"http://.../?name=%@&nameupdated=%@", name, nameUpdated];
NSMutableURLRequest *request;
NSString *webStringUrl = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url;
url = [NSURL URLWithString:webStringUrl];
assert(url != nil);
// Call down to the network manager so that it can set up its stuff
if (url != nil) {
request = [[NetworkManager sharedManager] requestToGetURL:url];
assert(request != nil);
}
RetryingHTTPOperation *updateOperation = [[[RetryingHTTPOperation alloc] initWithRequest:request] autorelease];
assert(updateOperation != nil);
[updateOperation setQueuePriority:NSOperationQueuePriorityNormal];
[[NetworkManager sharedManager] addNetworkManagementOperation:updateOperation finishedTarget:self action:@selector(updateItemOperationDone:)];
[urlString release];
如果名称字段类似于“Bed& Breakfast”,则url字符串最终为: http://.../?name=Bed%20&%20Breakfast& ....
我最终只以“床”为我的名字。
答案 0 :(得分:9)
使用以下代码对每个参数进行编码:
NSString *urlEncoded = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)sourceString,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
kCFStringEncodingUTF8);
然后从单独的URL编码片段构建完整的URL字符串。
答案 1 :(得分:7)
这只是以前使用ARC的代码的补充。这正确地连接起来:
NSString *urlEncoded = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)sourceString,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
kCFStringEncodingUTF8);
答案 2 :(得分:0)
url=(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)url, NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", kCFStringEncodingUTF8));
ARC的