ios 有没有办法将参数的 NSDictionary 附加到 NSURLRequest 而不是手动制作字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21299362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to attach a NSDictionary of parameters to an NSURLRequest instead of manually making a string?
提问by
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.
AFNetworking
允许您向NSDictionary
请求添加一个参数,并将它们附加到请求中。所以如果我想GET
用?q=8&home=8888
我做一个请求,我只会@{@"q": @"8", @"home": @"8888"}
非常简单地制作一个 NSDictionary 。
Is there a way to do this with NSURLSession
/ NSURLConnection
/ NSURLRequest
?
有没有办法用NSURLSession
/ NSURLConnection
/做到这一点NSURLRequest
?
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?
我知道我可以NSJSONSerialization
用于附加 JSON 数据,但是如果我只希望它们作为GET
URL 中的参数怎么办?我应该只添加一个类别吗?
回答by Peter DeWeese
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 和 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;
回答by bhavya kothari
TRY BELOW WORKING CODE
尝试以下工作代码
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"YOUR URL"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"44",@"UserId",@"0",@"NewsArticleId",@"",@"Date", nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
回答by Xuan
Example using NSURLSession:
使用 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];