NSMutableURLRequest获取-1012 http状态代码而不是401

时间:2017-09-05 19:13:41

标签: objective-c post http-status-codes nsmutableurlrequest

我必须在NSMutableURLRequest中传递授权令牌,我的查询是每当我必须传递正确令牌而不是我通过https状态(200 ..等)获得良好响应。但每当我必须传递错误的授权令牌时,我会得到以下http状态代码401的响应

*错误的令牌回复* (我隐藏了我的查询htpp:....)

错误域= NSURLErrorDomain代码= -1012“(null)”UserInfo = {NSErrorFailingURLStringKey = http ......,NSUnderlyingError = 0x60800024c420 {错误域= kCFErrorDomainCFNetwork代码= -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);

1 个答案:

答案 0 :(得分:0)

401是服务器生成的错误。 -1012是系统生成的错误。有时这可能是因为应用程序保留了缓存的证书,并且服务器上的证书已更改,因此它们不匹配。从应用程序的Caches清除Preferenceshome directory文件夹将删除旧的证书数据,应用程序必须从服务器下载新的证书数据,您的问题将得到解决。