从iPhone应用程序发出GET和POST请求 - 需要澄清

Gre*_*reg 5 iphone networking cocoa-touch http

我跟着这个有用的回答我的问题.

它似乎有效,但这里有两个问题:

  1. 如何检测HTTP错误?似乎没有调用didFailWithError方法?

更新: 它认为任何响应都是成功的.所以我想我必须在didRecieveResponse方法中处理HTTP错误,但除了告诉用户我遇到HTTP错误时出错,我是否需要以某种方式停止连接?和/或清理?

  1. 我在答案中看到这一行:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Run Code Online (Sandbox Code Playgroud)

我需要发布吗?在哪里,如何,何时?

los*_*sit 4

您将在 didReceiveResponse 中获得返回的状态代码

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSHTTPURLResponse *httpResponse;
    httpResponse = (NSHTTPURLResponse *)response;
    int statusCode = [httpResponse statusCode];
    //statusCode will be the http code returned like 201,500
 }
Run Code Online (Sandbox Code Playgroud)

要停止连接,请使用连接的类级变量。最好的方法是创建一个发送请求并接收响应的包装器。让您的视图控制器成为此类的委托,每当 didReceiveResponse 给出错误状态代码时,调用委托的适当方法并停止连接。

这是一个很好的包装类示例

http://kosmaczewski.net/projects/objective-c-rest-client/