本文介绍了获取webservice的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像的网址。当我在Safari的地址栏中键入它时,我会看到错误或确定等结果。



那么,如何在我的代码中正确调用该URL把结果作为字符串?



我尝试过 NSURLConnection NSURLRequest NSURLResponse 但我的响应对象始终是 nil

解决方案

这些类中的响应是指协议响应(HTTP标头等),而不是内容。 / p>

要获取内容,您有以下几种选择:


  1. 使用NSURLConnection异步模式:

  2. 在同步模式下使用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];


  3. 使用 [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:

  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.

这篇关于获取webservice的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 07:47