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

Ios 如何有效地设置http正文请求?,ios,nsdictionary,parameter-passing,key-value,http-request,Ios,Nsdictionary,Parameter Passing,Key Value,Http Request,在我的应用程序中,我当前正在从每个viewcontroller发送http请求。然而,目前我正在实现一个类,该类应该具有发送请求的方法 我的请求在参数数量上有所不同。例如,要获得tableview的列表,我需要将category、subcategory、filter和另外5个参数放入请求中 这就是我现在的请求: NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init]; [request setVa

在我的应用程序中,我当前正在从每个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 :)   
}

您可以使用以下内容从字典构造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:@"&"];
/*假设我们有一本
参数/值对*/
NSDictionary*参数=@{
@“排序”:@“某物”,
@“过滤器”:@“过滤器”,
@“类别”:“类别”
};
/*我们现在迭代字典
并将每一对附加到一个数组中
格式为=*/
NSMutableArray*pairs=[[NSMutableArray alloc]initWithCapacity:0];
for(NSString*输入参数){
[pairs addObject:[NSString stringWithFormat:@“%@=%@”,键,参数[key]];
}
/*我们终于加入了我们的数组对
使用“&”*/
NSString*requestParams=[pairs componentsJoinedByString:@“&”];
如果您记录
requestParams
字符串,您将得到:

过滤器=过滤器&类别=分类&排序=某物


PS我完全同意@rckoenes的观点,
AFNetworking
是这类操作的最佳解决方案。

看看,他们有一个
AFHTTPClient
,这将使这类调用非常容易。嗯,我喜欢你的解决方案,我担心使用AFNetworking之类的东西可能会导致拒绝我的应用程序。(这主要是因为我不确定他们是否使用了“违反”苹果规则的东西)我很高兴这对你有所帮助。关于
AFNetworking
,苹果没有办法拒绝你的应用程序(现在商店里肯定有数千个应用程序在使用它)。好吧,那我就试一试:)谢谢,也谢谢你!