AFNetworking
允许您向请求添加参数的NSDictionary
,它会将这些参数附加到请求中。所以,如果我想用?q=8&home=8888
做一个GET
请求,我只需要非常简单地创建一个像@{@"q": @"8", @"home": @"8888"}
这样的NSDictionary。
有没有办法用NSURLSession
/ NSURLConnection
/ NSURLRequest
实现这一点?
我知道我可以使用NSJSONSerialization
来追加JSON数据,但是如果我只想把它们作为GET
参数放在URL中,该怎么办呢?我应该只添加一个类别吗?
发布于 2015-09-18 03:11:56
您可以通过使用NSURLComponents和NSURLQueryItems更新url来完成此操作。在下面的示例中,假设已经在NSMutableURLRequest上设置了URL参数。您可以在使用它之前对其进行修改,以包括NSDictionary params
中的每个参数。请注意,每个参数在写入之前都会进行编码。
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;
发布于 2014-01-23 14:01:11
使用NSURLSession的示例:
NSURLSession *session = [NSURLSession sharedSession];
//populate json
NSDictionary *gistDict = @{@"files":@"test",@"description":@"test"};
NSError *jsonError;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:gistDict options:NSJSONWritingPrettyPrinted error:&jsonError];
//populate the json data in the setHTTPBody:jsonData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://yourURL"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
//Send data with the request that contains the json data
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Do your stuff...
}] resume];
https://stackoverflow.com/questions/21299362
复制相似问题