如何更改NSURLConnection sendSynchronousRequest以包括HTTPS连接的基本身份验证

问题描述

当前,下面的代码是我与服务器建立同步HTTP连接所必须的。 服务器基本上根据查询显示所需的UI对话框。 现在,服务器已更改为需要基本身份验证(用户名密码)的安全服务器。 您能帮我举个例子,将其更改为具有基本身份验证的HTTPS请求吗?

Nsstring *url = localhosturl;

Nsstring *path=[items[0] path];
path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]];

NSArray *myStrings = [[NSArray alloc] initWithObjects:url,syncportnum,query,path,nil];
Nsstring *targetUrl = [myStrings componentsJoinedByString:@""];


NSURL *url_1 = [NSURL URLWithString:targetUrl];

NSURLRequest *request1 = [NSURLRequest requestWithURL:url_1];


NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
Nsstring *responseString = [[Nsstring alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error,you should handle it here.
if(!error)
{
    //log response
    NSLog(@"Response from server = %@",responseString);
}

谢谢!

解决方法

这通常意味着将 URL 更改为

https://username:password@hostname/...

... 有一长串警告,例如用户名和密码将不可避免地在缓存中,强烈建议重写它以使用受支持的 API 异步执行相同的工作。 :-)