2016-04-26 267 views
0

我正在使用網絡連接。在POST請求中獲得未經授權的401。iOS Afnetworking:請求失敗未授權(401)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
    manager.requestSerializer = [AFJSONRequestSerializer serializer]; 
    //[manager.requestSerializer setValue:@"" forHTTPHeaderField:@"auth"]; 
    //[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    //[manager.requestSerializer setValue:@"Bearer \(token!)" forHTTPHeaderField:@"Authorization"]; 
    //sessionManager.requestSerializer.setValue("Bearer \(token!)", forHTTPHeaderField: "Authorization") 
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){ 
     NSLog(@"%@", responseObject); 
     } 
    } 
      failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    { 
     NSLog(@"%@", [error description]); 

    }]; 
+0

是您的應用可以正常使用移動數據? – Hasya

+1

我有同樣的問題。我正在從一個庫例程調用一個站點(SSL),它使用測試應用程序在它自己的工作區中工作,但是,一旦我嘗試在另一個應用程序中使用該庫,我會看到「請求失敗:未授權(401)」。 我已經嘗試了所有的TLS異常參數來規定這一點,特別是前向保密旁路,因爲我不確定我們的證書是否支持Forward Secrecy。似乎沒有任何工作。 –

回答

0

在您的.plist中,您是否添加了以下幾行?

<key>NSAppTransportSecurity</key> 
    <dict> 
      <key>NSAllowsArbitraryLoads</key><true/> 
    </dict> 
+0

http://stackoverflow.com/questions/34946791/app-transport-security-issue/34947223#34947223檢查這 –

+0

是這些行已經在我的plist –

0

使其使用這些,這個代碼將正常工作:

[request setValue:[dict valueForKey:@"Authorization"] 

forHTTPHeaderField:@"Authorization"]; 

示例代碼:

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; 

NSLog(@"%@",[dict valueForKey:@"Authorization"]); 

[request setValue:[dict valueForKey:@"Authorization"] 

forHTTPHeaderField:@"Authorization"]; 

//NSURLRequest *request =[NSURLRequest requestWithURL:url]; 

AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:request]; 

operation.responseSerializer =[AFJSONResponseSerializer serializer]; 

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 

{ 
success(responseObject); 

} 

failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

NSLog(@"Error: %@", error); 

id object = [NSJSONSerialization    JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponse DataErrorKey] options:NSJSONReadingMutableContainers error:nil]; 


NSLog(@"%@",object); 

failure(error); 

}]; 

[operation start]; 
+0

什麼是代碼中的字典? –

+0

Nsdictionary *字典 – parthiban

+0

你能告訴我什麼字典嗎?從哪裏**字典**獲取數據? –

0

我傾倒AFNetworking解決了這個問題,並使用NSUrlSession代替

相關問題