setValue:forHTTPHeaderField:@“Authorization”不起作用

时间:2013-11-28 13:53:49

标签: http-headers nsurlconnection

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

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>

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

1 个答案:

答案 0 :(得分:0)

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

NSString *authen = [NSString stringWithFormat:@"%@\\%@:%@", m_domain,
        m_account, m_password];
[request setValue:authen forHTTPHeaderField:@"Authorization"];

这项工作对我来说!