ASIHTTPRequest处理收到的服务器响应数据

来源:互联网 发布:手机facebook翻墙软件 编辑:程序博客网 时间:2024/04/27 21:21

获取HTTP状态码

ASIHTTPRequest并不对HTTP状态码做任何处理(除了重定向和授权状态码,下面会介绍到),所以你必须自己检查状态值并正确处理。

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request startSynchronous];int statusCode = [request responseStatusCode];NSString *statusMessage = [request responseStatusMessage];

 

读取响应头

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request startSynchronous];NSString *poweredBy = [[request responseHeaders] objectForKey:@"X-Powered-By"];NSString *contentType = [[request responseHeaders] objectForKey:@"Content-Type"];

 

处理文本编码

ASIHTTPRequest会试图读取返回数据的编码信息(Content-Type头信息)。如果它发现了编码信息,它会将编码信息设定为合适的 NSStringEncoding.如果它没有找到编码信息,它会将编码设定为默认编码(NSISOLatin1StringEncoding)。

当你调用[request responseString],ASIHTTPRequest会尝试以responseEncoding将返回的Data转换为NSString。

处理重定向

当遇到以下HTTP状态码之一时,ASIHTTPRequest会自动重定向到新的URL:

  • 301 Moved Permanently
  • 302 Found
  • 303 See Other

当发生重定向时,响应数据的值(responseHeaders,responseCookies,responseData,responseString等等)将会映射为最终地址的相应返回数据。

当URL发生循环重定向时,设置在这个URL上的cookie将被储存到全局域中,并在适当的时候随重定向的请求发送到服务器。

Cookies set on any of the urls encountered during a redirection cycle will be stored in the global cookie store, and will be represented to the server on the redirected request when appropriate.

你可以关闭自动重定向:将shouldRedirect设置为NO。

默认情况下,自动重定向会使用GET请求(请求体为空)。这种行为符合大多数浏览器的行为,但是HTTP spec规定301和302重定向必须使用原有方法。

要对301、302重定向使用原方法(包含请求体),在发起请求之前,设置shouldUseRFC2616RedirectBehaviour 为YES。

原创粉丝点击