我有一个像这样的网址here http://www.myserver.com/myservice.php?param=foobar。当我在 Safari 的地址栏中输入该内容时,我会看到类似“错误”或“正常”的结果。
那么,如何从代码中正确调用该 URL 并以字符串形式获取该结果?
我试过了NSURLConnection
, NSURLRequest
and NSURLResponse
但我的响应对象始终是nil
.
这些类中的“响应”指的是协议响应(HTTP 标头等),而不是内容。
要获取内容,您有以下几种选择:
- 以异步方式使用 NSURLConnection:使用 NSURLConnection http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
-
以同步模式使用 NSURLConnection:
// Error checks omitted
NSURL *URL = [NSURL URLwithString:@"http://www.myserver.com/myservice.php?param=foobar"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
-
Use [NSString stringWithContentsOfURL:]
NSURL *URL = [NSURL URLwithString:@"http://www.myserver.com/myservice.php?param=foobar"];
NSString *content = [NSString stringWithContentsOfURL:URL];
当然,你应该使用选项2和3only if您的内容将非常小,以保持响应能力。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)