[英]How to set http body request efficiently?
在我的应用程序中,我正在从每个viewcontroller发送http请求。 但是,当前我正在实现一个类,该类应该具有发送请求的方法。
我的要求参数数量不一。 例如,要获取tableview的事物列表,我需要将category,subcategory,filter和另外5个参数放入请求中。
这就是我现在的要求:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setValue:verifString forHTTPHeaderField:@"Authorization"];
[request setURL:[NSURL URLWithString:@"http://myweb.com/api/things/list"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSMutableString *bodyparams = [NSMutableString stringWithFormat:@"sort=popularity"];
[bodyparams appendFormat:@"&filter=%@",active];
[bodyparams appendFormat:@"&category=%@",useful];
NSData *myRequestData = [NSData dataWithBytes:[bodyparams UTF8String] length:[bodyparams length]];
[request setHTTPBody:myRequestData]
我的第一个想法是创建方法,接受所有这些参数,那些不需要的参数将为零,然后我将测试哪些是nil,而不是nil的那些将被附加到参数字符串(ms)。
然而,这是非常低效的。 后来,我开始考虑传递一些带有参数存储值的字典。 类似于带有nameValuePair的数组列表,在Android的Java中使用过。
我不确定,我如何从字典中获取密钥和对象
-(NSDictionary *)sendRequest:(NSString *)funcName paramList:(NSDictionary *)params
{
// now I need to add parameters from NSDict params somehow
// ?? confused here :)
}
您可以使用以下内容从字典构造params字符串:
/* Suppose that we got a dictionary with
param/value pairs */
NSDictionary *params = @{
@"sort":@"something",
@"filter":@"aFilter",
@"category":@"aCategory"
};
/* We iterate the dictionary now
and append each pair to an array
formatted like <KEY>=<VALUE> */
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params) {
[pairs addObject:[NSString stringWithFormat:@"%@=%@", key, params[key]]];
}
/* We finally join the pairs of our array
using the '&' */
NSString *requestParams = [pairs componentsJoinedByString:@"&"];
如果您记录requestParams
字符串,您将获得:
过滤= aFilter&类别= aCategory&排序=东西
PS我完全同意@rckoenes的说法, AFNetworking
是这种操作的最佳解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.