先说前提
我的app需要调用服务端的api,api的baseurl为“https://api.mydomain.com/api”(举个例子而已)
某个具体接口的路径是 “/user/getInfo”,
完整的路径就是 https://api.mydomain.com/api/user/getInfo
so,我的代码是
NSURL *baseURL = [NSURL URLWithString:@"https://api.mydomain.com/api"];
NSURL *relativeURL = [NSURL URLWithString:@"/user/getInfo" relativeToURL:baseURL];
而得到的结果是
https://api.mydomain.com/user/getInfo
/api 这段没了。。。。
为了搞清怎么拼接
各种试
NSURL *baseURL1 = [NSURL URLWithString:@"https://api.mydomain.com/api/"];
NSURL *baseURL2 = [NSURL URLWithString:@"https://api.mydomain.com/api"];
NSURL *relativeURL1 = [NSURL URLWithString:@"/user/getInfo" relativeToURL:baseURL1];
NSURL *relativeURL2 = [NSURL URLWithString:@"/user/getInfo" relativeToURL:baseURL2];
NSURL *relativeURL3 = [NSURL URLWithString:@"user/getInfo" relativeToURL:baseURL1];
NSURL *relativeURL4 = [NSURL URLWithString:@"user/getInfo" relativeToURL:baseURL2];
NSLog(@"1: %@", [relativeURL1 absoluteString]);
NSLog(@"2: %@", [relativeURL2 absoluteString]);
NSLog(@"3: %@", [relativeURL3 absoluteString]);
NSLog(@"4: %@", [relativeURL4 absoluteString]);
结果是
1: https://api.mydomain.com/user/getInfo
2: https://api.mydomain.com/user/getInfo
3: https://api.mydomain.com/api/user/getInfo
4: https://api.mydomain.com/user/getInfo
可见,只有第3种情况符合我们的预期
查一下RFC1808 Relative Uniform Resource Locators
原因找到了
1.如果baseulr没有以"/"结尾,则最后一个"/"的内容都会被忽略
2.如果relativeUrl以"/"开始,则被认为是从域名的根路径下开始,baseurl域名后的内容都会被忽略
所以
正确的用法是
1.baseurl要以"/"结尾
2.relativeUrl不能以"/"开始