【发布时间】:2018-02-14 03:44:13
【问题描述】:
我必须在 NSMutableURLRequest 中传递 Authorization 令牌,我的查询是每当我必须传递正确的令牌时,我就会得到 https 状态(200.. 等)的良好响应。但是每当我必须传递错误的授权令牌时,我都会收到以下响应,其中包含 http 状态代码 401
* 令牌响应错误 *(我隐藏了我的查询 htpp:....)
Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLStringKey=http......, NSUnderlyingError=0x60800024c420 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey ={url = http.....}}}, NSErrorFailingURLKey=http....}
** 这是我的代码 ** // 字典中的参数
NSDictionary *parameters = @{ @"user_id": [NSNumber numberWithInt:1]};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted
error:&error];
// Convert dictionary to Json String
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonparameter = jsonString;
}
NSData *postData = [jsonparameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:SiteAPIURL,wsname]]];
NSString *Accesstoken = [NSString stringWithFormat:@"Bearer %@",tokenInfo.access_token];
// Set Access token
[request setValue:Accesstoken forHTTPHeaderField:@"Authorization"];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse __autoreleasing *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"%@",error.localizedDescription);
NSLog(@"Status code =%ld",(long)response.statusCode);
【问题讨论】:
-
完全不相关,但是 (a) 您不必设置
Content-Length标头,因为这是为您完成的; (b) 不必取jsonData,将其转换为字符串,然后再转换回NSData。只需将HTTPBody设置为jsonData; (c) 除非您需要支持早于NSURLSession的操作系统版本,否则您应该真正停用NSURLConnection而不要进行同步请求。 -
您没有收到 -1012 状态码。那是错误代码,即
NSURLErrorUserCancelledAuthentication。您将错误与在下一行打印的状态代码混淆了。错误后打印的状态码是什么? -
错误后我得到状态码 = null
-
好的,那么显然授权错误正在阻止
NSHTTPURLResponse捕获任何状态代码。 -
能否请您简单解释一下,我该怎么做才能获得http状态码401?,谢谢
标签: objective-c post http-status-codes nsmutableurlrequest