今天,我遇到了NSURLConnection
的问题。我想下载网址http://api.wunderground.com/api/fs3a45dsa345/geolookup/q/34.532900,-122.345.json
的内容。如果我只是将URL粘贴到Safari中,我会得到正确的响应。但是,如果我对NSURLConnection
做同样的事情,我会收到“未找到”的回复。这是我正在使用的代码:
NSURL *requestURL = [[NSURL alloc] initWithString:@"same url as above"];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:requestURL];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self
startImmediately:YES];
这里有什么问题?
答案 0 :(得分:2)
确保您通过发送stringByAddingPercentEscapesUsingEncoding:
消息来转义URL字符串中的任何特殊字符,例如:
NSString *s = [@"some url string" stringByAddingPercentEscapesUsingEncoding:NSUTFStringEncoding];
NSURL *requestURL = [NSURL URLWithString:s];
修改强>
事实证明,Web服务请求失败,因为默认情况下未设置 User-Agent 标头。要设置它,请使用NSMutableURLRequest
而不是NSURLRequest
的实例来创建请求,如下所示:
NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:myURL];
[myRequest setValue:@"My App" forHTTPHeaderField:@"User-Agent"];
答案 1 :(得分:0)
委托代码在哪里?对于异步NSURLConnection
,需要一个delegate
方法来接收返回的数据。其他选项包括sendSynchronousRequest
:或者必须在sendSynchronousRequest
中异步包装GCD block
。