在iOS中,如何从Web服务器接收响应的http状态代码(404,500 200等)。我假设它在NSUrlConnectionDelegate中。
Objective-C或 Monotouch .NET回答确定。
答案 0 :(得分:87)
是的,您可以在委托方法-didRecieveResponse中获取状态代码:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode];
}
答案 1 :(得分:11)
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)。
答案 2 :(得分:3)
以下是如何在MonoTouch for .NET中为这些C#用户执行此操作。它位于 NSUrlConnectionDelegate 。
中public override void ReceivedResponse (NSUrlConnection connection, NSUrlResponse response)
{
if (response is NSHttpUrlResponse)
{
var r = response as NSHttpUrlResponse;
Console.WriteLine (r.StatusCode);
}
}
答案 3 :(得分:1)
查看this other stackoverflow question,您似乎可以在- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response
委托方法中处理http状态代码:
- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse*)response
{
if ([response isKindOfClass: [NSHTTPURLResponse class]])
statusCode = [(NSHTTPURLResponse*) response statusCode];
}