ASIHttpRequest - how to convert NSDictionary of params to url-encoded query param string?

随声附和 提交于 2020-01-06 04:51:11

问题


What is the preferred way to make a GET request with ASIHttpRequest using query params provided as an NSDictionary. How do I get from NSDictionary *params
to ?param1=value1&param2=value2 (percent-encoded)

Obviously I can construct the query part of the URL manually but it seems like there is probably a better way.

Thanks!


回答1:


You must pass the query string as part of the URL. From the ASIHTTPRequest interface on GitHub:

// The url for this operation, should include GET params in the query string where appropriate
NSURL *url; 

If you don't want to roll your own dictionary-to-query-string method, take a look at the GTMNSDictionary+URLArguments category in Google Toolbox for Mac (.h, .m). It adds a method, gtm_httpArgumentString, to NSDictionary that should be what you're after.




回答2:


I am not using ASIHTTPRequest, but I have a similar need for a URLRequest I make. Here is what I am doing:

- (NSString *) createParamString 
{
    NSDictionary *params = // build up the param dictionary    
    NSString *result = @"";
    id key;
    NSEnumerator *enumerator = [params keyEnumerator];
    while (key = [enumerator nextObject]) {
        result = [result stringByAppendingFormat:@"%@=%@&", key, [params objectForKey:key]];
    }
    result = [result substringToIndex:[result length] - 2];
    return [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
}

Not sure if it's perfect for all situations, but it's working well enough for me



来源:https://stackoverflow.com/questions/7060692/asihttprequest-how-to-convert-nsdictionary-of-params-to-url-encoded-query-para

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