Objective-C - 格式化 GET 请求
Objective-C - Formatting GET request
GET请求中%JOHN%等字符串参数的传递规则是什么url
我的请求 url 应该是这样的: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: 无
尝试#2:
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%JOE%"]];
**O/P:
https://somesite.com/search/name?name=JOE
有什么建议吗?
您可以使用 NSURLComponents
构建网址:
Objective-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
属性。
你弄错了,只用一个%@
。
示例:
NSString *string = @"JOE";
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%@",string]];
GET请求中%JOHN%等字符串参数的传递规则是什么url
我的请求 url 应该是这样的: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: 无
尝试#2:
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%JOE%"]];
**O/P:
https://somesite.com/search/name?name=JOE
有什么建议吗?
您可以使用 NSURLComponents
构建网址:
Objective-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
属性。
你弄错了,只用一个%@
。
示例:
NSString *string = @"JOE";
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"https://somesite.com/search/name?name=%@",string]];