从iPhone应用程序进行GET和POST请求 - 需要澄清 [英] Making GET and POST Requests from an iPhone Application - Clarification Needed

查看:116
本文介绍了从iPhone应用程序进行GET和POST请求 - 需要澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我随同这个有用的回答我的问题



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


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

UPDATE: 它认为任何回复成功。所以我想我必须处理HTTP错误didRecieveResponse方法,但除了告诉用户有一个错误,当我碰到HTTP错误,我需要停止连接不知何故?


  1. 我在回答中看到这一行:
  2. ol>


      [[NSURLConnection alloc] initWithRequest:request delegate:self]; 


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

    解决方案

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

       - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse * httpResponse;
    httpResponse =(NSHTTPURLResponse *)response;
    int statusCode = [httpResponse statusCode];
    // statusCode将是返回的http代码201,500
    }

    停止连接,对连接使用类级变量。最好的办法是创建一个发送请求和接收响应的包装器。使你的viewcontroller成为这个类的一个委托,每当didReceiveResponse给出错误状态代码,调用委托的适当方法并停止连接。



    这是一个好的包装类示例



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


    I'm following along with this useful looking answer to my question.

    It seems to be working, but here are two questions I have:

    1. How do I detect an HTTP error? The didFailWithError method doesn't seem to be getting called?

    UPDATE: It considers any response a success. So I guess I have to handle HTTP errors in the didRecieveResponse method, but besides telling the user there was an error when I hit an HTTP error, do I need stop the connection somehow? And/or cleanup?

    1. I see this line in the answer:

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    

    Do I need to release that? Where, how, when?

    解决方案

    You will get the status code returned in the 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
     }
    

    For stopping the connection, use a class-level variable for the connection. The best way to go about it would be create a wrapper which sends requests and receives response. Make your viewcontroller a delegate of this class and whenever the didReceiveResponse gives an error status code, call the appropriate method of the delegate and stop the connection.

    Here's a good wrapper class example

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

    这篇关于从iPhone应用程序进行GET和POST请求 - 需要澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆