0
NSString *login = @"Web Guest";
NSString *password = @"xxxxx";
NSError *myError = nil;

NSLog(@"CONNECTION: Adding credentials");

NSURLCredential *credential = [NSURLCredential credentialWithUser:login
                                                         password:password
                                                      persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                         initWithHost:@"54.225.xxx.xxx"
                                         port:80
                                         protocol:@"http"
                                         realm:@"54.225.xxx.xxx" 
                                         authenticationMethod:NSURLAuthenticationMethodDefault];

//Not sure if set up correctly

[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];   

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"xx.xxx.xxx.xxx/blah"]
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                   timeoutInterval:12];

NSLog(@"CONNECTION: Running request");

//Perform the request
NSURLResponse *response;

NSData *data = [NSURLConnection
                sendSynchronousRequest:request
                returningResponse:&response
                error:&myError];

此时,我收到错误“由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'+ [NSString stringWithCString:encoding:]:NULL cString'”

NSString *result = [NSString stringWithCString:[data bytes] encoding:NSUTF8StringEncoding];

NSLog(@"Webserver response: %@", result);

我正在尝试从需要使用基本身份验证进行授权的 Web 服务器返回一些 JSON,但似乎在设置它时遇到了一些麻烦。我是 Objective-c 编程和 ios 开发的新手,但非常感谢任何帮助!谢谢。

4

1 回答 1

0

您没有在请求 URL 字符串中使用方案:@"xx.xxx.xxx.xxx/blah"。你需要像 @" https://xx.xxx.xxx.xxx/blah " 这样的东西,否则 [NSURL URLWithString:] 返回 nil。

于 2013-06-26T17:30:14.627 回答