encoding – 如何对NSString进行URL编码

栏目: IOS · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/15443040/how-to-url-encode-a-nsstring

我试图url编码一个字符串,但NSURLConnection失败,因为’坏网址’.这是我的网址:

NSString *address = mp.streetAddress;
    NSString *encodedAddress = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *cityState= mp.cityState;
    NSString *encodedCityState = [cityState stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *fullAddressURL = [NSString stringWithFormat:@"http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<X1-ZWz1bivd5de5mz_8xo7s>&address=%@&citystatezip=%@", encodedAddress, encodedCityState];
    NSURL *url = [NSURL URLWithString:fullAddressURL];

以下是API调用URL的示例:

下面是调用API的地址匹配“2114 Bigelow Ave”,“Seattle,WA”的地址的示例:

http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<ZWSID>&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA

由于某种原因,此URL无法连接.有人可以帮我吗?

您必须先编码fullAddressURL,然后再将其发送到NSURL,而不是编码地址& cityState个别.

NSString *address = @"2114 Bigelow Ave";
//NSString *encodedAddress = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *cityState= @"Seattle, WA";
// NSString *encodedCityState = [cityState stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString *fullAddressURL = [NSString stringWithFormat:@"http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<X1-ZWz1bivd5de5mz_8xo7s>&address=%@&citystatezip=%@", address, cityState];
fullAddressURL = [fullAddressURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"fullAddressURL: %@",fullAddressURL);

NSURL *url = [NSURL URLWithString:fullAddressURL];

我测试了上面的代码,它给出了与给定链接相同的输出http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=\u0026lt;ZWSID\u0026gt;\u0026amp;address=2114 Bigelow Ave& citystatezip = Seattle ,华盛顿州

翻译自:https://stackoverflow.com/questions/15443040/how-to-url-encode-a-nsstring


以上所述就是小编给大家介绍的《encoding – 如何对NSString进行URL编码》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Compilers

Compilers

Alfred V. Aho、Monica S. Lam、Ravi Sethi、Jeffrey D. Ullman / Addison Wesley / 2006-9-10 / USD 186.80

This book provides the foundation for understanding the theory and pracitce of compilers. Revised and updated, it reflects the current state of compilation. Every chapter has been completely revised ......一起来看看 《Compilers》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具