问题描述
我有一个像的网址。当我在Safari的地址栏中键入它时,我会看到错误或确定等结果。
那么,如何在我的代码中正确调用该URL把结果作为字符串?
我尝试过 NSURLConnection
, NSURLRequest
和 NSURLResponse
但我的响应对象始终是 nil
。
这些类中的响应是指协议响应(HTTP标头等),而不是内容。 / p>
要获取内容,您有以下几种选择:
- 使用NSURLConnection异步模式:
-
在同步模式下使用NSURLConnection:
//错误检查省略
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];
-
使用
[NSString stringWithContentsOfURL:]
NSURL * URL = [NSURL URLwithString:@http://www.myserver.com/myservice.php?param =取得foobar];
NSString * content = [NSString stringWithContentsOfURL:URL];
当然,你应该使用选项2和3 仅当您的内容尺寸非常小时才能保持响应能力。
I've got an URL like here. When I type that into Safari's address bar I see an result like "Error" or "OK".
So, how do I properly call that URL from within my code and get that result as a string?
I've tried it with NSURLConnection
, NSURLRequest
and NSURLResponse
but my response object is always nil
.
The "response" in those classes refers to the protocol response (HTTP headers, etc.), not the content.
To get the content, you have a few options:
- Use NSURLConnection in asynchronous mode: Using NSURLConnection
Use NSURLConnection in synchronous mode:
// 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];
Of course, you should use options 2 and 3 only if your content will be really small in size, to maintain responsiveness.
这篇关于获取webservice的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!