iphone - iPhone 中的 HTTP 身份验证

标签 iphone ios http authentication

我希望有人能帮我解决一个与 Xcode 中的身份验证有关的问题 基本上我有一个返回 XML 的 MS Sharepoint 服务器。 我有这段代码用于身份验证,但无法访问。

NSString *urlString = @"http://example.com/";

NSMutableURLRequest *request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *str1 = [NSString stringWithString:@"username:password"];
NSData *myDate = [str1 dataUsingEncoding:NSUTF8StringEncoding];
NSString *str2 = [Base64 encode:myDate];
NSLog(@"%@ str1 %@", str2,str1);

[request addValue:[NSString stringWithFormat:@"Basic %@",str2] forHTTPHeaderField:@"Authorization"];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);

即使我传递了正确的凭据,但服务器不接受。 它返回

401 - 未经授权:由于凭据无效,访问被拒绝。

任何人都可以帮忙吗?

最佳答案

使用 NSURLConnection-connection:didReceiveAuthenticationChallenge: 委托(delegate)方法检测何时需要身份验证。简而言之,您将使用 NSURLCredential 实例将身份验证附加到请求。

文档有很好的概述和代码示例:

Responding to an Authentication Challenge

关于iphone - iPhone 中的 HTTP 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5821121/

相关文章:

ios - 如何动态计算 UILabel 高度

ios - iPad 应用程序方向和重新定位问题

iphone - 从 iPhone 应用程序访问私有(private) Web 服务

http - 如何使用 apache camel 将消息发送到多个目的地?

iphone - 在 XCode 4.2 空应用程序模板中使用 Interface Builder 将 tabbarcontroller 添加到 AppDelegate 的步骤

iphone - self.interfaceOrientation 导致在 iOS 4.x 上调用 shouldAutorotateToInterfaceOrientation

http - 如何在 http 请求正文中发送 bool 值或 int 值?

android - honeycomb中执行Http post报错

ios - 清除 reloadData 上的 tableView 不起作用?

ios - iOS 版 Google Analytics 中的线程崩溃