ios NSUrlConnectionDelegate - 获取 http 状态代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6918760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSUrlConnectionDelegate - Getting http status codes
提问by Ian Vink
in iOS, how can I receive the http status code (404,500 200 etc) for a response from a web server. I am assuming it's in the NSUrlConnectionDelegate.
在 iOS 中,如何从 Web 服务器接收响应的 http 状态代码(404,500 200 等)。我假设它在 NSUrlConnectionDelegate 中。
Objective-C or Monotouch.NET answer ok.
Objective-C 或Monotouch.NET 回答确定。
回答by Vladimir
Yes, you can get status code in delegate method -didRecieveResponse:
是的,您可以在委托方法 -didRecieveResponse 中获取状态代码:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode];
}
回答by Manuel
NSHTTPURLResponse* urlResponse = nil;
NSError *error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
The aSynchronous request should also have a way to get the NSHTTPURLResponse..
aSynchronous 请求也应该有办法获得 NSHTTPURLResponse..
You get the status code like this:
你会得到这样的状态代码:
int statusCode = [urlResponse statusCode];
int errorCode = error.code;
In the case of some much used error codes (like 404) it will get put in the error but with a different code (401 will be -1012).
在一些经常使用的错误代码(如 404)的情况下,它会被放入错误但具有不同的代码(401 将是 -1012)。
回答by Ian Vink
Here's how to do it in MonoTouch for .NET for those C# users. THis is in the NSUrlConnectionDelegate.
下面是如何在 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);
}
}
回答by Carter
Looking at this other stackoverflow questionit looks like you can handle http status codes in the - (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response
delegate method:
查看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];
}