2

基本認証を使用して https Web サービス (RESTful) を呼び出そうとしています。URL自体に資格情報を入力しても問題なく動作しますが、例外などでパスワードが表示されないように、リクエストに追加したいと思います。

次のコードを使用しています。

    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myuser"
                                                             password:@"mypassword"
                                                          persistence:NSURLCredentialPersistenceForSession];

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                             initWithHost:@"example.com"
                                             port:443
                                             protocol:@"https"
                                             realm:nil
                                             authenticationMethod:NSURLAuthenticationMethodHTTPBasic];


    [[NSURLCredentialStorage sharedCredentialStorage]  setDefaultCredential:credential
                                                        forProtectionSpace:protectionSpace];

    NSURLConnection *theConnection = [NSURLConnection  connectionWithRequest:theRequest delegate:self];

しかし、それは機能しません。didReceiveAuthenticationChallengeデリゲート メソッドが呼び出され、そこに資格情報を追加できますが、理想的には、要求と共に送信します。

何か案は?

4

2 に答える 2

2

基本認証の場合は、ヘッダーで資格情報を送信してみてください。毎回私のために働きます。

リクエストのヘッダーでユーザー名とパスワードを送信するため

NSString *authString = [[NSString stringWithFormat:@"%@:%@", userName, password] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalAuth = base64 of authString;

リクエストで、フィールド名Authorizationと値を含むヘッダーを追加します"Basic " + finalAuth

于 2010-03-09T14:04:56.510 に答える
0

NSURLConnection を使用しているコードの最後の行を見逃していました。デリゲートが応答していることを確認してください:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

そして、protectionSpace に対して YES を返しています。

また、デリゲートが以下に応答していることを確認してください。

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

NSURLAuthenticationChallengeここで、作成した資格情報をに、proposedCredential プロパティに割り当てることができます。また、NSURLProtectionSpaceインスタンスを の protectionSpace プロパティに割り当てることもできますNSURLAuthenticationChallenge

于 2010-03-12T08:17:00.297 に答える