29

在 Objective-C 中获取 url 减去其查询字符串的最佳方法是什么?一个例子:

输入:

http://www.example.com/folder/page.htm?param1=value1&param2=value2

输出:

http://www.example.com/folder/page.htm

有没有NSURL我想念的方法来做到这一点?

4

11 回答 11

47

从 iOS 8/OS X 10.9 开始,使用 NSURLComponents 有一种更简单的方法。

NSURL *url = [NSURL URLWithString:@"http://hostname.com/path?key=value"];
NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];

urlComponents.query = nil; // Strip out query parameters.
NSLog(@"Result: %@", urlComponents.string); // Should print http://hostname.com/path
于 2015-01-24T11:46:52.483 回答
38

我看不到 NSURL 方法。您可以尝试以下方法:

NSURL *newURL = [[NSURL alloc] initWithScheme:[url scheme]
                                         host:[url host]
                                         path:[url path]];

测试看起来不错:

#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
    NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];

    NSURL *url = [NSURL URLWithString:@"http://www.abc.com/foo/bar.cgi?a=1&b=2"];
    NSURL *newURL = [[[NSURL alloc] initWithScheme:[url scheme]
                                              host:[url host]
                                              path:[url path]] autorelease];
    NSLog(@"\n%@ --> %@", url, newURL);
    [arp release];
    return 0;
}

运行它会产生:

$ gcc -lobjc -framework Foundation -std=c99 test.m ; ./a.out 
2010-11-25 09:20:32.189 a.out[36068:903] 
http://www.abc.com/foo/bar.cgi?a=1&b=2 --> http://www.abc.com/foo/bar.cgi
于 2010-11-24T22:20:54.380 回答
18

这是安德烈答案的 Swift 版本,带有一些额外的味道 -

extension NSURL {

    func absoluteStringByTrimmingQuery() -> String? {
        if var urlcomponents = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) {
            urlcomponents.query = nil
            return urlcomponents.string
        }
        return nil
    }
}

你可以这样称呼它——

let urlMinusQueryString  = url.absoluteStringByTrimmingQuery()
于 2016-08-17T11:42:12.353 回答
7

斯威夫特版本

extension URL {
    func absoluteStringByTrimmingQuery() -> String? {
        if var urlcomponents = URLComponents(url: self, resolvingAgainstBaseURL: false) {
            urlcomponents.query = nil
            return urlcomponents.string
        }
        return nil
    }
}

希望这可以帮助!

于 2017-10-25T12:36:21.497 回答
3

您可能需要的是 url 的主机和路径组件的组合:

NSString *result = [[url host] stringByAppendingPathComponent:[url path]];
于 2010-11-24T22:18:59.510 回答
3

您可以尝试使用queryofNSURL获取参数,然后使用stringByReplacingOccurrencesOfStringof去除该值NSString

NSURL *before = [NSURL URLWithString:@"http://www.example.com/folder/page.htm?param1=value1&param2=value2"];
NSString *after = [before.absoluteString stringByReplacingOccurrencesOfString:before.query withString:@""];

请注意,最终 URL 仍将以 ? 结尾,但如果需要,您也可以轻松删除它。

于 2014-04-25T00:13:14.943 回答
2

我想-baseURL可能会做你想做的事。

如果没有,您可以像这样进行往返NSString

NSString *string = [myURL absoluteString];
NSString base = [[string componentsSeparatedByString:@"?"] objectAtIndex:0];
NSURL *trimmed = [NSURL URLWithString:base];
于 2010-11-24T22:17:53.300 回答
2

NSURL有一个query属性,其中包含?GET url 之后的所有内容。因此,只需从 absoluteString 的末尾减去它,您就得到了没有查询的 url。

NSURL *originalURL = [NSURL URLWithString:@"https://winker@127.0.0.1:1000/file/path/?q=dogfood"];
NSString *strippedString = [originalURL absoluteString];
NSUInteger queryLength = [[originalURL query] length];
strippedString = (queryLength ? [strippedString substringToIndex:[strippedString length] - (queryLength + 1)] : strippedString);
NSLog(@"Output: %@", strippedString);

日志:

Output: https://winker@127.0.0.1:1000/file/path/

+1是针对?不属于的query

于 2012-11-16T11:19:03.567 回答
0

你可能会喜欢这个类的replaceOccurrencesOfString:withString:options:range:方法NSMutableString。我通过编写一个类别来解决这个问题NSURL

#import <Foundation/Foundation.h>

@interface NSURL (StripQuery)
// Returns a new URL with the query stripped out.
// Note: If there is no query, returns a copy of this URL.
- (NSURL *)URLByStrippingQuery;
@end

@implementation NSURL (StripQuery)
- (NSURL *)URLByStrippingQuery
{
    NSString *query = [self query];
    // Simply copy if there was no query. (query is nil if URL has no '?',
    // and equal to @"" if it has a '?' but no query after.)
    if (!query || ![query length]) {
        return [self copy];
    }
    NSMutableString *urlString = [NSMutableString stringWithString:[self absoluteString]];
    [urlString replaceOccurrencesOfString:query
                               withString:@""
                                  options:NSBackwardsSearch
                                    range:NSMakeRange(0, [urlString length])];
    return [NSURL URLWithString:urlString];
}
@end

这样,我可以将此消息发送到现有NSURL对象并让一个新NSURL对象返回给我。

我使用以下代码对其进行了测试:

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURL *url = [NSURL URLWithString:@"http://www.example.com/script.php?key1=val1&key2=val2"];
//      NSURL *url = [NSURL URLWithString:@"http://www.example.com/script.php?"];
//      NSURL *url = [NSURL URLWithString:@"http://www.example.com/script.php"];
        NSURL *newURL = [url URLByStrippingQuery];
        NSLog(@"Original URL: \"%@\"\n", [url absoluteString]);
        NSLog(@"Stripped URL: \"%@\"\n", [newURL absoluteString]);
    }
    return 0;
}

我得到以下输出(减去时间戳):

Original URL: "http://www.example.com/script.php?key1=val1&key2=val2"
Stripped URL: "http://www.example.com/script.php?"

请注意,问号 ('?') 仍然存在。我将把它留给读者以安全的方式将其删除。

于 2012-09-07T15:51:03.823 回答
0

我们应该尝试使用 NSURLComponents

  NSURL *url = @"http://example.com/test";
  NSURLComponents *comps = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:YES];
  NSString *cleanUrl = [NSString stringWithFormat:@"%@://%@",comps.scheme,comps.host];
  if(comps.path.length > 0){
     cleanUrl = [NSString stringWithFormat:@"%@/%@",cleanUrl,comps.path];
  }
于 2018-11-21T07:21:55.020 回答
-1

我想你要找的是baseUrl.

于 2010-11-24T22:17:34.427 回答