iOS:如何进行正确的 URL 编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12652396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:30:56  来源:igfitidea点击:

iOS : How to do proper URL encoding?

iosurl-encoding

提问by Hemang

I'm unable to open a URL into UIWebViewso I've seached & found that I need to encode URL, so I tried to encode it but, I've facing problem in URL encoding : My URL is http://somedomain.com/data/Témp%20Page%20-%20Open.html(It's not real URL).

我无法打开 URL,UIWebView所以我搜索并发现我需要对 URL 进行编码,所以我尝试对其进行编码,但是,我在 URL 编码方面遇到了问题:我的 URL 是http://somedomain.com/data/Témp%20Page%20-%20Open.html(它不是真正的 URL)。

I'm concerned with %20that I tried to replace using stringByReplacingOccuranceOfString:@"" withString:@"", it give me the URL I wanted like http://somedomain.com/data/Témp Page - Open.htmlHowever its not opening in UIWebViewbut amazingly it opens in Safari& FireFoxperfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.

我很担心%20,我试着用替换stringByReplacingOccuranceOfString:@"" withString:@"",它给我的网址,我想喜欢http://somedomain.com/data/Témp Page - Open.html但是它不是在打开UIWebView,但令人惊讶它在打开SafariFireFox完善。即使我打开未编码的 URL,它也会自动转换并打开我正在寻找的页面。

I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, http%3A%2F%2Fsomedomain.com%2Fdata%2FT...which can't open in UIWebViewand even in any browser.

我用谷歌搜索 URL 编码 & 它指向我已经检查过的不同结果,但没有结果帮助我!!我在不同的 URL 编码问题中尝试了不同的函数答案,但它只是更改了所有特殊字符并使我的 URL 像,http%3A%2F%2Fsomedomain.com%2Fdata%2FT...无法UIWebView在任何浏览器中甚至在任何浏览器中打开。

It gives the following Error Login UIWebView delegate

它提供了以下Error LogUIWebView delegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }

Error Code : 101 & Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn't be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}

错误代码:101 & 描述:错误域=WebKitErrorDomain 代码=101“操作无法完成。(WebKitErrorDomain 错误 101。)” UserInfo=0x6e4cf60 {}

采纳答案by Mattias Wadman

I did some tests and I think the problem is not really with the UIWebViewbut instead that NSURLwon't accept the URL because of the é in "Témp" is not encoded properly. This will cause +[NSURLRequest requestWithURL:]and -[NSURL URLWithString:]to return nilas the string contains a malformed URL. I guess that you then end up using a nilrequest with -[UIViewWeb loadRequest:]which is no good.

我做了一些测试,我认为问题并不在于UIWebView,而是NSURL因为“Témp”中的 é 未正确编码而无法接受 URL。这将导致+[NSURLRequest requestWithURL:]-[NSURL URLWithString:]返回,nil因为字符串包含格式错误的 URL。我猜你最终会使用一个不好的nil请求-[UIViewWeb loadRequest:]

Example:

例子:

NSLog(@"URL with é: %@", [NSURL URLWithString:@"http://host/Témp"]);
NSLog(@"URL with encoded é: %@", [NSURL URLWithString:@"http://host/T%C3%A9mp"]);

Output:

输出:

2012-10-02 12:02:56.366 test[73164:c07] URL with é: (null)
2012-10-02 12:02:56.368 test[73164:c07] URL with encoded é: http://host/T%C3%A9mp

If you really really want to borrow the graceful handling of malformed URLs that WebKit has and don't want to implement it yourself you can do something like this but it is very ugly:

如果你真的想借用 WebKit 对格式错误的 URL 的优雅处理并且不想自己实现它,你可以做这样的事情,但它非常难看:

UIWebView *webView = [[[UIWebView alloc]
                       initWithFrame:self.view.frame]
                      autorelease];

NSString *url = @"http://www.httpdump.com/texis/browserinfo/Témp.html";

[webView loadHTMLString:[NSString stringWithFormat:
                         @"<script>window.location=%@;</script>",
                         [[[NSString alloc]
                           initWithData:[NSJSONSerialization
                                         dataWithJSONObject:url
                                         options:NSJSONReadingAllowFragments
                                         error:NULL]
                           encoding:NSUTF8StringEncoding]
                          autorelease]]
                baseURL:nil];

回答by Hemang

The answer @Dhaval Vaishnani provided is only partially correct. This method treats the ?, =and &characters as not to be encoded, since they're valid in an URL. Thus, to encode an arbitrary string to be safely used as a part of an URL, you can't use this method. Instead you have to fall back to using CoreFoundation and CFURLRef:

@Dhaval Vaishnani 提供的答案只是部分正确。此方法将?,=&字符视为未编码,因为它们在 URL 中有效。因此,要将任意字符串编码为安全地用作 URL 的一部分,您不能使用此方法。相反,您必须回退到使用 CoreFoundation 和CFURLRef

NSString *unsafeString = @"this &string= confuses ? the InTeRwEbZ";
CFStringRef safeString = CFURLCreateStringByAddingPercentEscapes (
    NULL,
    (CFStringRef)unsafeString,
    NULL,
    CFSTR("/%&=?$#+-~@<>|\*,.()[]{}^!"),
    kCFStringEncodingUTF8
);

Don't forget to dispose of the ownership of the resulting string using CFRelease(safeString);.

不要忘记使用 处理结果字符串的所有权CFRelease(safeString);

Also, it seems that despite the title, OP is looking for decodingand not encodinga string. CFURLRefhas another, similar function call to be used for that:

此外,似乎尽管标题,OP 正在寻找解码而不是编码字符串。CFURLRef有另一个类似的函数调用可用于:

NSString *escapedString = @"%32%65BCDEFGH";
CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (
    NULL,
    (CFStringRef)escapedString,
    CFSTR(""),
    kCFStringEncodingUTF8
);

Again, don't forget proper memory management.

同样,不要忘记适当的内存管理。

回答by jclv

The most straightforward way is to use:

最直接的方法是使用:

NSString *encodedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iDhaval was close, but he was doing it the other way around (decoding instead of encoding).

iDhaval接近,但他身边做它的其他方式(而不是解码编码)。

Anand's way would work, but you'll most likely have to replace more characters than spaces and new lines. See the reference here: http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters

阿南德的方式将工作,但你很可能不得不更换不是空格和换行多个字符。请参阅此处的参考:http: //en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters

Hope that helps.

希望有帮助。

回答by iDhaval

It's very simple to encode the URL in iPhone. It is as following

在 iPhone 中对 URL 进行编码非常简单。它如下

NSString* strURL = @"http://somedomain.com/data/Témp Page - Open.html";

NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

It's a perfect way to encode the URL, I am using it and it's perfectly work with me.

这是编码的URL一个完美的方式,我用它和它的完美的工作和我在一起。

Hope it will help you!!!

希望能帮到你!!!

回答by Hemang

This may useful to someone who's reach to this question for URL encoding, as my question likely different which has been solved and accepted, this is the way I used to do encoding,

这可能对解决 URL 编码问题的人有用,因为我的问题可能与已解决并接受的问题不同,这是我过去进行编码的方式,

-(NSString *)encodeURL:(NSString *)urlString
{
    CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:@&=+@,/?#[]"), kCFStringEncodingUTF8);
    return (NSString *)CFBridgingRelease(newString);
}

回答by nithinreddy

You can try this

你可以试试这个

NSString *url = @"http://www.abc.com/param=Hi how are you";

NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:
 NSASCIIStringEncoding];

回答by Mrug

I think this will work for you

我认为这对你有用

[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]

the Native method for URL Encoding.

URL 编码的本机方法。

回答by Hemang

Swift 4.x

斯威夫特 4.x

let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)

回答by Michael

You probably need to break the URL down into it's constituent parts and then URL encode the host and path but not the scheme. Then put it back together again.

您可能需要将 URL 分解为其组成部分,然后对主机和路径进行 URL 编码,而不是对方案进行编码。然后再把它装回去。

Create an NSURL with the string and then use the methods on it such as host, scheme, path, query, etc to pull it apart. Then use CFURLCreateStringByAddingPercentEscapes to encode the parts and then you can put them back together again into a new NSURL.

使用字符串创建一个 NSURL,然后使用其上的方法(如主机、方案、路径、查询等)将其分开。然后使用CFURLCreateStringByAddingPercentEscapes编码的部分,然后你可以把它们重新结合在一起到一个新的NSURL。

回答by Anand

can you please Try this out.

你能试试这个吗?

    //yourURL contains your Encoded URL
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSLog(@"Keyword:%@ is this",yourURL);

I am not sure,but I have solved using this in my case. Hope this will solve yours.

我不确定,但我已经解决了在我的情况下使用它的问题。希望这能解决你的问题。