如何有效地设置HTTP身体请求?

在我的应用程序中,我目前正在从每个viewcontroller发送http请求。 但是,目前我正在实现一个类,这应该有发送请求的方法。

我的要求在参数数量上有所不同。 例如,要得到tableview的东西的列表,我需要把类别,子类别,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] 

我的第一个想法是创build方法,接受所有这些参数,那些不需要的将是零,那么我会testing哪些是零,那些不是零将附加到参数string(毫秒)。

然而这是相当低效的。 后来我正在考虑传递一些带有存储值的字典作为参数。 像在Android的Java中使用nameValuePair的数组列表。

我不知道,我将如何获得我的字典中的键和对象

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

你可以用一个像这样的字典来构造你的paramsstring:

 /* 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:@"&"]; 

如果你loggingrequestParamsstring,你会得到:

过滤= aFilter&类别= aCategory&sorting=东西

PS我完全同意@ rckoenes的AFNetworking是这种操作的最佳解决scheme。