有时我们需要获取请求地址的相关信息,这时我们就可以用 NSURL 的一些方法操作来获取它。
需要注意的一点是:请求地址里可能存在特殊字符或中文,为了正确获取信息,建议使用 stringByAddingPercentEscapesUsingEncoding: 对字符串进行编码,然后对应的使用 stringByReplacingPercentEscapesUsingEncoding: 对字符串进行解码。
main.m
1 #import <Foundation/Foundation.h> 2 3 void testURL(NSString *strUrl) { 4 strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //对字符串进行编码 5 6 NSURL *url = [NSURL URLWithString:strUrl]; 7 NSMutableString *mStrInfo = [[NSMutableString alloc] initWithString:@"URL相关信息如下:\n"]; 8 [mStrInfo appendFormat:@"absoluteString: %@\n", [url absoluteString]]; 9 [mStrInfo appendFormat:@"relativeString: %@\n", [url relativeString]]; 10 [mStrInfo appendFormat:@"baseURL: %@\n", [url baseURL]]; 11 [mStrInfo appendFormat:@"absoluteURL: %@\n", [url absoluteURL]]; 12 [mStrInfo appendFormat:@"scheme: %@\n", [url scheme]]; 13 [mStrInfo appendFormat:@"resourceSpecifier: %@\n", [url resourceSpecifier]]; 14 [mStrInfo appendFormat:@"host: %@\n", [url host]]; 15 [mStrInfo appendFormat:@"port: %@\n", [url port]]; 16 [mStrInfo appendFormat:@"user: %@\n", [url user]]; 17 [mStrInfo appendFormat:@"password: %@\n", [url password]]; 18 [mStrInfo appendFormat:@"path: %@\n", [url path]]; 19 [mStrInfo appendFormat:@"fragment: %@\n", [url fragment]]; //编码后的字符串,获取到的值为null,而不是正常情况的a=1;最终a=1被作为query的值内容了 20 [mStrInfo appendFormat:@"parameterString: %@\n", [url parameterString]]; 21 [mStrInfo appendFormat:@"query: %@\n", [url query]]; 22 [mStrInfo appendFormat:@"relativePath: %@\n", [url relativePath]]; //如果baseURL是nil,relativePath就跟path一样 23 [mStrInfo appendFormat:@"pathComponents: %@\n", [url pathComponents]]; 24 25 NSLog(@"%@", [mStrInfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]); //对字符串进行解码 26 } 27 28 int main(int argc, const char * argv[]) { 29 @autoreleasepool { 30 NSString *strUrl = @"http://www.cnblogs.com:80/huangjianwu/archive/2015/06.html?author=KenmuHuang黄&page=1#a=1"; 31 testURL(strUrl); 32 } 33 return 0; 34 }
结果:
1 2015-06-19 23:17:29.496 OCNSURL[768:34254] URL相关信息如下: 2 absoluteString: http://www.cnblogs.com:80/huangjianwu/archive/2015/06.html?author=KenmuHuang黄&page=1#a=1 3 relativeString: http://www.cnblogs.com:80/huangjianwu/archive/2015/06.html?author=KenmuHuang黄&page=1#a=1 4 baseURL: (null) 5 absoluteURL: http://www.cnblogs.com:80/huangjianwu/archive/2015/06.html?author=KenmuHuang黄&page=1#a=1 6 scheme: http 7 resourceSpecifier: //www.cnblogs.com:80/huangjianwu/archive/2015/06.html?author=KenmuHuang黄&page=1#a=1 8 host: www.cnblogs.com 9 port: 80 10 user: (null) 11 password: (null) 12 path: /huangjianwu/archive/2015/06.html 13 fragment: (null) 14 parameterString: (null) 15 query: author=KenmuHuang黄&page=1#a=1 16 relativePath: /huangjianwu/archive/2015/06.html 17 pathComponents: ( 18 "/", 19 huangjianwu, 20 archive, 21 2015, 22 "06.html" 23 )
时间: 2024-10-20 05:27:01