How can I get NSURLResponse body?

江枫思渺然 提交于 2019-12-04 08:15:12

问题


I'm writing an application that connect with a server using NSURLConnection.

In the delegate method didreceiveresponse, if the status code is 404, I cancel the connection and I would like to show a message with a custom error that is generated in the server.

The problem is that from response object, I only can get statuscode, headers, mimetype, etc. but no body.

How do I get the body message from NSURLResponse?


回答1:


Why do you cancel the connection? After all, 404 can have content body as well. Just don't cancel it, and let the program call the next delegate NSURLConnection method. When the data [the content body] is sent - (void)connection:(NSURLConnection *) didReceiveData:(NSData *) is called, you need to retrieve the data there. Read corresponding part in the docs:

The response from a server to a request can be viewed as two parts: metadata describing the contents and the URL content data. The metadata that is common to most protocols is encapsulated by the NSURLResponse class and consists of the MIME type, expected content length, text encoding (where applicable), and the URL that provided the response.

The NSURLConnection and NSURLDownload classes provide the interface to make a connection specified by an NSURLRequest object and download the contents. An NSURLConnection object provides data to the delegate as it is received from the originating source, whereas an NSURLDownload object writes the request data directly to disk. Both classes provide extensive delegate support for responding to redirects, authentication challenges, and error conditions.

As for an example delegate implementation:

-   (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
    NSLog(@"String sent from server %@",[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]);

}


来源:https://stackoverflow.com/questions/3014206/how-can-i-get-nsurlresponse-body

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