Http headers 设置值:用于HttpHeaderField:@";“授权”;不起作用

Http headers 设置值:用于HttpHeaderField:@";“授权”;不起作用,http-headers,nsurlconnection,Http Headers,Nsurlconnection,我正在尝试连接到需要用户名和密码进行身份验证的服务器。我的代码如下: NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[NS

我正在尝试连接到需要用户名和密码进行身份验证的服务器。我的代码如下:

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"username:password" forHTTPHeaderField:@"Authorization"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
但这不起作用,我总是收到一条错误消息:

title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
title>401需要授权
需要授权
此服务器无法验证您是否
您有权访问该文档
请求。要么你提供的是错误的
凭据(例如,错误的密码)或您的
浏览器不了解如何提供
所需的凭据


当我尝试连接到一个不需要身份验证的服务器时,这段代码非常有效。那么,如何正确设置用户名和密码呢?

您应该指定服务器的域,请尝试以下格式:

NSString *authen = [NSString stringWithFormat:@"%@\\%@:%@", m_domain,
        m_account, m_password];
[request setValue:authen forHTTPHeaderField:@"Authorization"];
这是我的工作