如何在iPhone编程中使用身份验证挑战发送HTTP客户端请求



我正在尝试发送具有身份验证安全性的http请求。它将以 JSON 格式给出响应。我正在寻找任何用于发送 http 请求以获取响应的教程或示例代码。我已经搜索过,但没有获得任何有用的教程。请帮帮我,提前谢谢。

假设您想从服务中获取数据并且您有URl For That,因此以下方法将从给定的URL中的服务器获取数据

-(NSString *)getDataFromService:(NSString *)strUrl{

NSURL *url = [NSURL URLWithString:strUrl];
NSString *response;

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

[request setDelegate:self];
[request addBasicAuthenticationHeaderWithUsername:USERNAME
                                      andPassword:PASSWORD];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
   response = [request responseString];
}
else
{
    response=nil;
}
return response;

}

所以在响应字符串中,你有来自给定 url 服务器的响应数据。

为此,您需要从名为ASIHTTPRequest的github中加载库,这是链接

http://allseeing-i.com/ASIHTTPRequest/How-to-use

你可以实现"NSURLConnectionDataDelegate"。在你的.h文件中做类似的事情

@interface youClass : NSObject<NSURLConnectionDataDelegate>

在您的 .h 文件中实现"NSURLConnectionDataDelegate"的委托方法

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:    (NSURLProtectionSpace *)protectionSpace {
      //    NSLog(@"canAuthenticateAgainstProtectionSpace:");
      return [protectionSpace.authenticationMethod         isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:    (NSURLAuthenticationChallenge *)challenge {
    //    NSLog(@"didReceiveAuthenticationChallenge:");
    [challenge.sender useCredential:[NSURLCredential     credentialForTrust:challenge.protectionSpace.serverTrust]     forAuthenticationChallenge:challenge];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
     //    NSLog(@"connectionDidFinishLoading");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    //    NSLog(@"Recived data!!!");
}

希望这有帮助。 :)

最新更新