【问题标题】:How to set http body request efficiently?如何有效地设置http body请求?
【发布时间】:2014-02-27 23:45:09
【问题描述】:

在我的应用程序中,我目前正在从每个视图控制器发送 http 请求。但是,目前我正在实现一个类,它应该具有发送请求的方法。

我的请求在参数数量上有所不同。例如,要获取 tableview 的列表,我需要将类别、子类别、过滤器和另外 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 :)   
}

【问题讨论】:

  • 看看AFNetworking,他们有一个AFHTTPClient,这将使此类呼叫变得非常容易。

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


【解决方案1】:

你可以用这样的方式从字典中构造你的参数字符串:

/* 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 字符串,您将获得:

filter=aFilter&category=aCategory&sort=something

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

【讨论】:

  • 嗯,我喜欢你的解决方案,我担心使用 AFNetworking 之类的东西可能会导致我的应用程序被拒绝。 (这主要是因为我不确定他们是否没有使用“违反”苹果规则的东西)
  • 很高兴这对您有所帮助。关于AFNetworking,Apple 不可能拒绝你的应用(现在商店里肯定有成千上万的应用在使用它)。
  • 好的,我会试一试 :) 谢谢,也谢谢你 rckoenes!
猜你喜欢
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 2011-06-24
相关资源
最近更新 更多