Get content of webservice

早过忘川 提交于 2019-12-02 17:38:28

问题


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.


回答1:


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:

  1. Use NSURLConnection in asynchronous mode: Using NSURLConnection
  2. 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];
    
  3. 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.



来源:https://stackoverflow.com/questions/3249897/get-content-of-webservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!