NSUrlConnectionDelegate – 获取http状态码

在iOS中,如何从Web服务器接收http状态码(404,500 200等)。 我假设它在NSUrlConnectionDelegate。

Objective-C或Monotouch .NET的答案确定。

是的,你可以在委托方法中获得状态码-didRecieveResponse:

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; int code = [httpResponse statusCode]; } 
 NSHTTPURLResponse* urlResponse = nil; NSError *error = nil; responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; 

aSynchronous请求也应该有一个获取NSHTTPURLResponse的方法。

你得到这样的状态代码:

 int statusCode = [urlResponse statusCode]; int errorCode = error.code; 

在一些大量使用的错误代码(如404)的情况下,它将被置于错误中,但使用不同的代码(401将是-1012)。

这是如何在这些C#用户的MonoTouch for .NET中实现的。 这是在NSUrlConnectionDelegate

 public override void ReceivedResponse (NSUrlConnection connection, NSUrlResponse response) { if (response is NSHttpUrlResponse) { var r = response as NSHttpUrlResponse; Console.WriteLine (r.StatusCode); } } 

看看这个其他的stackoverflow问题,它看起来像你可以在- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response处理http状态码- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response委托方法:

 - (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse*)response { if ([response isKindOfClass: [NSHTTPURLResponse class]]) statusCode = [(NSHTTPURLResponse*) response statusCode]; }