8

我正在尝试对字符串进行 url 编码,但 NSURLConnection 由于“错误的 url”而失败。这是我的网址:

    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 的示例:

下面是一个为精确地址匹配“2114 Bigelow Ave”、“Seattle, WA”的地址调用 API 的示例:

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

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

4

1 回答 1

18

您必须先编码您的 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=<ZWSID>&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA

于 2013-03-16T04:06:52.437 回答