encoding – 如何对NSString进行URL编码

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

内容简介:翻译自: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编码》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

互联网浪尖上的女性

互联网浪尖上的女性

田玉翠 / 人民出版社 / 2017-1 / 68.00

二十三个真实、前沿的女性创业者实例,带你走进“她世界”洞悉“她经济”。《互联网浪尖上的女性》不仅仅关于创业,更是关于女性如何追逐自己的梦想,让人生更丰满、更精彩。一起来看看 《互联网浪尖上的女性》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具