带参数的 Afnetworking 2
Posted
技术标签:
【中文标题】带参数的 Afnetworking 2【英文标题】:Afnetworking 2 with parameters 【发布时间】:2014-03-10 05:32:35 【问题描述】:我对 ios 开发真的很陌生..我只想从我的 Web 服务中获得一些 JSON 响应。当我搜索它时,我发现 AFnetworking 对此很有用。所以我下载了它并做了一个示例应用程序。但我需要将一些参数传递给服务。我的服务有两个参数 [用户名和密码]。我的网址是这样的
http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser
谁能给我一些代码示例,如何将我的参数传递给该服务以获取 json 响应?
我已经尝试过这段代码.. 但它不会接受参数.. 一些人在谈论 AFHTTPClient.. 但我使用的是 AFN 2.0.. 这里没有类调用 AFHTTPCLient .. 我在这里很容易......请帮帮我
NSURL *url = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/textsearch/json?query=restuarants+in+sydney&sensor=false&key=AIzaSyDn9a-EvJ875yMxZeINmUP7CwbO9YT1w2s"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
// 3
self.googlePlaces = [responseObject objectForKey:@"results"];
[self.tableView reloadData];
// NSLog(@"JSON RESULT %@", responseObject);
self.weather = (NSDictionary *)responseObject;
self.title = @"JSON Retrieved";
[self.tableView reloadData];
failure:^(AFHTTPRequestOperation *operation, NSError *error)
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
];
// 5
[operation start];
编辑:
我已经使用下面的代码段解决了我的问题...
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"47", @"caregiverPersonId", nil];
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:@"your full url goes here"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject)
NSLog(@"JSON: %@", [responseObject description]);
failure:^(AFHTTPRequestOperation *operation, NSError *error)
NSLog(@"Error: %@", [error description]);
];
【问题讨论】:
在 2.0 中,您可以使用AFHTTPRequestOperationManager
而不是 AFHTTPClient
。然后您可以使用POST
或GET
(或任何适合您的网络服务的东西)。
非常感谢您的指导,此链接解决了我的问题***.com/questions/20047090/…
【参考方案1】:
试试这个
-(void)login
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithCapacity:3];
[dict setObject:_usernameTextField.text forKey:@"userName"];
[dict setObject:_passwordTextField.text forKey:@"password"];
AFHTTPClient *client=[[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:@""]];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"];
client.parameterEncoding = AFJSONParameterEncoding;
[client postPath:@"GetValidUser" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
NSDictionary *op=(NSDictionary *)responseObject;
NSLog(@"%@",op);
failure:^(AFHTTPRequestOperation *operation, NSError *error)
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:MESSAGE_EN message:@"Unable to login. Please try again." delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
[alert show];
NSLog(@"error.localizedDescription %@",error.localizedDescription);
];
注意:请使用正确的值填写字段并尝试。 dict 是输入后数据
【讨论】:
这是 AFNetworking 1.x。在 2.x 中,您可以使用AFHTTPRequestOperationManager
。
你能根据AFN 2更新答案吗?
感谢您的指导,我已经通过此链接解决了这个问题***.com/questions/20047090/…【参考方案2】:
我从 SO question 的某个地方得到了这个。看到这个:
- (IBAction)loginButtonPressed
NSURL *baseURL = [NSURL URLWithString:@"http://myweb.mobile.com/WebServices/AppointmentService.asmx"];
//build normal NSMutableURLRequest objects
//make sure to setHTTPMethod to "POST".
//from https://github.com/AFNetworking/AFNetworking
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:@"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text], kUsernameField,
[passwordTextField text], kPasswordField,
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
path:@"http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser" parameters:params];
//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
//"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
//see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
//mattt's suggestion http://***.com/a/9931815/1004227 -
//-still didn't prevent me from receiving plist data
//[httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject)
NSString *response = [operation responseString];
NSLog(@"response: [%@]",response);
failure:^(AFHTTPRequestOperation *operation, NSError *error)
NSLog(@"error: %@", [operation error]);
];
//call start on your request operation
[operation start];
[httpClient release];
希望这会有所帮助.. :)
编辑
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
[formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding]
name:@"email"];
[formData appendPartWithFormData:[pass dataUsingEncoding:NSUTF8StringEncoding]
name:@"password"];
// etc.
success:^(AFHTTPRequestOperation *operation, id responseObject)
NSLog(@"Response: %@", responseObject);
failure:^(AFHTTPRequestOperation *operation, NSError *error)
NSLog(@"Error: %@", error);
];
【讨论】:
是的,但由于我使用的是 AFN 2,所以没有名为 AFHTTPClient 的类...我该怎么办? 我已经关注了它......但我只想知道如何使用 AFN 2 传递我的参数 :( :( 请有人帮助我 那个教程只使用了一个没有参数的 url.. 我想将我的参数传递给 web 服务 我会尝试..谢谢你的帮助 是的...我会为其他人发布我的代码 :) 谢谢您的帮助..实际上它与您指示我的有点不同.. 但它有助于我理解 :)【参考方案3】:使用下面的代码
NSDictionary *paramDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"first_Object",@"first_Key",@"second_Object",@"second_Key" nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:@"YOUR_URL_STRING" parameters:paramDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) Success responce failure:^(AFHTTPRequestOperation *operation, NSError *error) failure responce];
如果你愿意,你可以设置
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
【讨论】:
以上是关于带参数的 Afnetworking 2的主要内容,如果未能解决你的问题,请参考以下文章
如何在上传带参数的图像时使用 AFNetworking 2.0 设置 cookie?
AFNetworking 在格式化 JSON 时将我的双打转换为带引号的字符串