代码之家  ›  专栏  ›  技术社区  ›  flohei

获取webservice的内容

  •  0
  • flohei  · 技术社区  · 16 年前

    我有一个像这样的网址 here . 当我在Safari的地址栏中输入时,我会看到一个类似“Error”或“OK”的结果。

    那么,如何从代码中正确地调用该URL并将结果作为字符串获得呢?

    我试过了 NSURLConnection NSURLRequest NSURLResponse nil .

    1 回复  |  直到 11 年前
        1
  •  1
  •   Can Berk Güder Pugalmuni    16 年前

    这些类中的“response”指的是协议响应(HTTP报头等),而不是内容。

    要获取内容,您有几个选项:

    1. 在异步模式下使用NSURLConnection: Using NSURLConnection
    2. // 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. 使用 [NSString stringWithContentsOfURL:]

      NSURL *URL = [NSURL URLwithString:@"http://www.myserver.com/myservice.php?param=foobar"];
      NSString *content = [NSString stringWithContentsOfURL:URL];
      

    当然,您应该使用选项2和3 您的内容将非常小的大小,以保持响应能力。