【发布时间】:2015-02-09 15:28:26
【问题描述】:
我正在使用这种方式 API 登录我的应用程序。
NSString *url = [NSString stringWithFormat:@"%@//login",xyz];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
NSLog(@"Error creating JSON object: %@", [error localizedDescription]);
}
[request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:APIKEY forHTTPHeaderField:@"X_API_KEY"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
// the NSOperationQueue upon which the handler block will be dispatched:
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: data options: 0 error: &error]; //I am using sbjson to parse
if(httpResponse.statusCode == 200)
{
//Show message to user success
}
else if(httpResponse.statusCode == 401)
{
//Show message to user -fail
}
else if(httpResponse.statusCode == 500)
{
//Show message to user- server error
}
}];
当我使用正确的用户名和密码时,我得到 httpResponse 和状态码为 200。但如果使用错误的用户名和密码,我不会得到 401。
那么如何处理这种情况
问候 兰吉特
【问题讨论】:
-
401 听起来像是对错误凭据的合理响应,但是是什么让您确定这是服务器的设计?也许响应正文包含一个线索。
-
@danh,正如您在上面的代码中看到的那样,我正在根据状态代码检查它,截至目前我没有收到任何状态代码,当凭据错误时,我确实收到错误代码:104 响应。所以你建议我在检查时使用它?
标签: ios nsurlconnection sendasynchronousrequest