如何有效地设置http正文请求?

时间:2012-12-19 15:42:11

标签: ios nsdictionary parameter-passing key-value http-request

在我的应用中,我正在发送来自每个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,那些不是nil的那些将被附加到参数字符串(ms )。

然而,这是非常低效的。 后来我在考虑传递一些带有参数存储值的字典。像在android的java中使用的nameValuePair的数组列表。

我不确定,我如何从字典中获取密钥和对象

    -(NSDictionary *)sendRequest:(NSString *)funcName paramList:(NSDictionary *)params 
{
  // now I need to add parameters from NSDict params somehow
  // ?? confused here :)   
}

1 个答案:

答案 0 :(得分:7)

你可以用字典构造你的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是这种操作的最佳解决方案。

相关问题