我最近跟着CodeSchool课程学习iOS,他们建议使用AFNetworking与服务器进行交互.
我试图从我的服务器获取一个JSON,但我需要将一些参数传递给网址.我不希望将这些参数添加到URL,因为它们包含用户密码.
对于简单的URL请求,我有以下代码:
NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/usersignin"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"NSError: %@",error.localizedDescription);
}];
[operation start];
Run Code Online (Sandbox Code Playgroud)
我已经检查了NSURLRequest的文档,但从那里得不到任何有用的东西.
如何将用户名和密码传递给此请求以在服务器中读取?
你可以使用AFHTTPClient:
NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
NSURLRequest *request = [client requestWithMethod:@"POST" path:@"usersignin" parameters:@{"key":@"value"}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"NSError: %@",error.localizedDescription);
}];
[operation start];
Run Code Online (Sandbox Code Playgroud)
理想情况下,您需要子类化AFHTTPClient并使用其postPath:parameters:success:failure:方法,而不是手动创建操作并启动它.
| 归档时间: |
|
| 查看次数: |
9349 次 |
| 最近记录: |