Objective-C - 格式化GET请求

时间:2016-08-17 21:39:57

标签: objective-c nsurlconnection

在GET请求网址

中传递字符串参数(例如%JOHN%)的规则是什么

我的请求网址应该是:https://somesite.com/search/name?name=%SEARCH_KEYWORD%

尝试#1:我做了这个

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%%%@%%",SEARCH_KEYWORD]];

O / P: nil

尝试#2:

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%JOE%"]];

** O / P:

https://somesite.com/search/name?name=JOE

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您可以使用NSURLComponents构建网址:

目标-C:

NSURLComponents *components = [NSURLComponents componentsWithString:@"https://google.com"];
components.query = @"s=%search keywords%"

NSURL *url = components.URL;

Swift(在生产中小心!,我以前在Playgrounds测试):

let components = NSURLComponents(string: "https://google.com")!
components = "s=%search keywords%"

let url = components!
print(url) // "https://google.com?s=%25search%20keywords%25"

此外,如果您需要更复杂的查询,NSURLComponent具有queryItems属性。

答案 1 :(得分:-3)

你犯了一个错误,只需使用一个%@。 示例:

NSString *string = @"JOE";
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%@",string]];