如何编码NSURL中的尖锐符号

时间:2012-06-01 19:19:07

标签: objective-c nsurl

我有这种情况,我需要向远程服务器发送GET http请求。我使用NSURLConnection并在HTTPScoop中拦截请求。

网址格式如下:

http://domain.com?key=username##somehash&url=someotherurl.com

我这样做:

NSString *urlString = [[NSString alloc]init];
urlString = @"http://domain.com?key=username##somehash&url=someotherurl.com";
NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:encodedString]]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"GET"];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

在这种情况下,我没有逃过#符号,我在httpscoop中看到的请求是:

http://domain.com?key=username223somehash&url=someotherurl.com

如果我将尖锐的符号转移到%23,它会在httpscoop中出现类似的内容:

http://domain.com?key=username22523somehash&url=someotherurl.com

我尝试了不同的组合,但总是有尖锐的标志问题。这有什么好转的吗?谢谢!

1 个答案:

答案 0 :(得分:1)

将#替换为%23(source)。

编辑 - 哎呀,没看到你的其余信息。不确定NSURL,但我之前在使用NSURL的URL中编码参数时遇到了困难。我最终使用了ASIHTTPRequest,它负责处理所有编码问题。我建议做同样的事情。