有没有办法将NSDictionary参数附加到NSURLRequest而不是手动创建字符串? [英] Is there any way to attach a NSDictionary of parameters to an NSURLRequest instead of manually making a string?
问题描述
AFNetworking
允许您向请求添加 NSDictionary
参数,并将它们附加到请求中。所以如果我想用做一个
我只是做一个NSDictionary像 GET
请求?q = 8& home = 8888 @ {@q:@8,@home:@8888}
非常简单。
AFNetworking
allows you to add an NSDictionary
of parameters to a request, and it will append them to the request. So if I wanted to do a GET
request with ?q=8&home=8888
I'd just making an NSDictionary like @{@"q": @"8", @"home": @"8888"}
very simply.
有没有办法用 NSURLSession
/ NSURLConnection
/ NSURLRequest
?
Is there a way to do this with NSURLSession
/ NSURLConnection
/ NSURLRequest
?
我知道我可以使用 NSJSONSerialization
来附加JSON数据,但是如果我只想在URL中将它们作为 GET
参数?我应该只添加一个类别吗?
I know I can use NSJSONSerialization
for appending JSON data, but what if I just want them as GET
parameters in the URL? Should I just add a category?
推荐答案
您可以通过使用NSURLComponents和NSURLQueryItems更新网址来完成此操作。在以下示例中,假设已在NSMutableURLRequest上设置了URL参数。您可以在使用它来包含NSDictionary params
中的每个参数之前对其进行修改。请注意,每个参数在写入之前都会进行编码。
You can do this by updating the url using NSURLComponents and NSURLQueryItems. In the following example, assume that the URL parameter has already been set on an NSMutableURLRequest. You can modify it before using it to include each parameter from the NSDictionary params
. Note that each parameter is encoded before it is written.
NSURLComponents *url = [[NSURLComponents alloc] initWithURL:request.URL resolvingAgainstBaseURL:YES];
NSMutableArray *queryItems = NSMutableArray.new;
[params enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {
[queryItems addObject:[NSURLQueryItem queryItemWithName:name
value:[value stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]]];
}];
url.queryItems = queryItems;
request.URL = url.URL;
这篇关于有没有办法将NSDictionary参数附加到NSURLRequest而不是手动创建字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!