How to set http body request efficiently?

心已入冬 提交于 2019-12-10 10:56:45

问题


in my app, I'm currently sending http requests from each viewcontroller. However, currently I'm implementing one class, that is supposed to have method for sending requests.

My requests vary in number of parameters. For example, to get list of things for tableview I need to put category, subcategory, filter and 5 more parameters into request.

This is what my request looks like now:

    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]

My first idea was to create method, that accepts all of these parameters, and those, which are not needed would be nil, then I would test which are nil and those which are not nil would be appended to parameter string (ms).

This is however pretty inefficient. Later on I was thinking about passing some dictionary with stored values for a parameter. Something like array list with nameValuePair that's used in android's java.

I'm not sure, how would I get keys and objects from my dictionary

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

回答1:


You could construct your params string from a dictionary with something like this:

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

If you log the requestParams string you will get:

filter=aFilter&category=aCategory&sort=something

PS I totally agree with @rckoenes that AFNetworking is the best solution for this kind of operations.



来源:https://stackoverflow.com/questions/13955930/how-to-set-http-body-request-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!