简体   繁体   中英

NSURLCredential not working for synchronuos request in iphone

I am using Synchronous request and passing the credentials but I am getting authentication error in response. Below is my code of request and response from server.

Request:-

NSURLCredential *userCredentials = [NSURLCredential  credentialWithUser:@"username"
                                                               password:@"paswd"
                                                            persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:@"http://webaddress.inc.com"
                                                                    port:80
                                                                protocol:@"http"
                                                                   realm:@"webaddress.inc.com"
                                                    authenticationMethod:nil];

[[NSURLCredentialStorage sharedCredentialStorage] setCredential:userCredentials
                                             forProtectionSpace:space];

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://webaddress.inc.com"]
                                                          cachePolicy:NSURLCacheStorageNotAllowed
                                                      timeoutInterval:30];


NSURLResponse *response;
NSError *error;

NSData *returnData = [NSURLConnection sendSynchronousRequest:urlRequest
                                           returningResponse:&response
                                                       error:&error];

/////////// Response

401 Authorization Required


Note: If I am sending the request with async request it is working fine as in that case is giving them the required credentials when asked for. 会在要求时向其提供所需的凭据。

I am sure there might be something missing in my code.

Waiting for your valuable inputs.

Have you ever tried ASIHTTPRequest which makes easier http operations in IPhone enviroment. And It has really simple and good documentation. I used to use it inside of my projects, It was working awesome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM