【发布时间】:2013-11-28 13:53:49
【问题描述】:
我正在尝试连接到需要用户名和密码进行身份验证的服务器。我的代码如下:
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>
当我尝试连接到不需要身份验证的服务器时,此代码运行良好。那么,如何正确设置用户名和密码呢?
【问题讨论】:
标签: http-headers nsurlconnection