如何获得NSURLResponse正文? [英] How can I get NSURLResponse body?

查看:666
本文介绍了如何获得NSURLResponse正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用NSURLConnection与服务器连接的应用程序.

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

在委托方法didreceiveresponse中,如果状态代码为404,我将取消连接,并且希望显示一条消息,其中包含服务器中生成的自定义错误.

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.

问题在于,我只能从响应对象中获取状态码,标头,mimetype等,而没有正文.

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

如何从NSURLResponse获取正文消息?

How do I get the body message from NSURLResponse?

推荐答案

为什么取消连接?毕竟,404也可以具有内容主体.只是不要取消它,而是让程序调用下一个委托NSURLConnection方法. 当发送数据[内容主体] - (void)connection:(NSURLConnection *) didReceiveData:(NSData *)时,您需要在那里检索数据. 阅读文档中的相应部分 :

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:

服务器对请求的响应可以看成两个部分:描述内容的元数据和URL内容数据. NSURLResponse类封装了大多数协议通用的元数据,该元数据由MIME类型,预期的内容长度,文本编码(如果适用)以及提供响应的URL组成.

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.

NSURLConnection和NSURLDownload类提供了一个接口,以建立由NSURLRequest对象指定的连接并下载内容. NSURLDownload对象将请求数据直接写入磁盘.这两个类都为响应重定向,身份验证挑战和错误情况提供了广泛的委托支持.

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.

作为示例委托实现:

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

}

这篇关于如何获得NSURLResponse正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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