如何爲GET請求編碼url字符串?我特別遇到了一個問題,我想發送的字段的值包含&符號(&),它被解釋爲字段之間的分隔符。如何使用NSMutableURLRequest對GET請求中的特殊字符進行編碼
我目前正在創建我的要求如下(這實際上使呼叫從蘋果的MVC組網示例所採取的代碼,所以它可能是不相關的這個問題,但爲了保持完整性)
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];
如果名稱字段是像「牀&早餐」,那麼URL字符串結束爲: http://.../?name=Bed%20&%20Breakfast& ....
和我結束了唯一的「牀」是我的名字。
NSString *urlEncoded = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)sourceString,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
kCFStringEncodingUTF8);
然後構建從單獨的URL編碼片段的完整URL字符串:
嗨..For我,我有編碼+在發送請求。我已經通過去除除了+這樣的所有字符發送請求..的NSString *了urlencoded =(的NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)sourceString, NULL, (CFStringRef)@ 「+」, kCFStringEncodingUTF8);.對某人有幫助,並感謝Ole Begemann。重要的是這是爲ARC啓用的項目。 –