IOS开发之CFURLCreateStringByAddingPercentEscapes--URL 编码

来源:互联网 发布:百度bae域名404 编辑:程序博客网 时间:2024/05/29 19:58


#define SINA_API_AUTHORIZE          @"https://api.weibo.com/oauth2/authorize"

#define SINA_APP_KEY                @"3456404324"


- (NSURL*)getOauthCodeUrl {                //获取auth_code or access_token;留给webview

    //https://api.weibo.com/oauth2/authorize

    //https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI

     NSMutableDictionary *params = [NSMutableDictionarydictionaryWithObjectsAndKeys:

 SINA_APP_KEY,                   @"client_id",       //申请的appkey

@"token",                       @"response_type",   //access_token

 @"http://hi.baidu.com/jt_one",   @"redirect_uri",   //申请时的重定向地址

 @"mobile",                      @"display",         //web页面的显示方式

                                        nil];

NSURL *url = [selfgenerateURL:SINA_API_AUTHORIZE params:params];    //参数是可变个数的

NSLog(@"url= %@",url);

    return url;

}



- (NSURL *)generateURL:(NSString *)baseURL params:(NSDictionary *)params {

if (params) {

NSMutableArray *pairs = [NSMutableArrayarray];

for (NSString *keyin params.keyEnumerator) {

NSString *value = [paramsobjectForKey:key];

            //将要添加到URL的字符串进行特殊处理,如果这些字符串含有 & 这些特殊字符,用“%+ASCII” 代替

NSString *escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(

 NULL, /* allocator */

 (CFStringRef)value,

 NULL, /* charactersToLeaveUnescaped */

 (CFStringRef)@"!*'();:@&=+$,/?%#[]",

  kCFStringEncodingUTF8);

                [pairs addObject:[NSStringstringWithFormat:@"%@=%@", key, value]];

[escaped_valuerelease];

}

NSString *query = [pairscomponentsJoinedByString:@"&"];

NSString *url = [NSStringstringWithFormat:@"%@?%@", baseURL, query];

return [NSURLURLWithString:url];

} else {

return [NSURLURLWithString:baseURL];

}

}


原创粉丝点击