如何通过 POST 和 AFNetworking 以变量形式发送数据?
Posted
技术标签:
【中文标题】如何通过 POST 和 AFNetworking 以变量形式发送数据?【英文标题】:How to sent data in variable via POST and AFNetworking? 【发布时间】:2014-01-16 01:02:29 【问题描述】:我用这个方法:
NSDictionary *params = @@"email" : email,
@"password" : pass
;
NSString* HOST_URL = @"http://server.com:8080";
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:HOST_URL]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
path:@"/login"
parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
NSDictionary *response = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:operation.responseData options:kNilOptions error:nil];
//HERE YOU HAVE A RESPONSE (your server answer)
failure:^(AFHTTPRequestOperation *operation, NSError *error)
NSLog(@"Error: %@", error.localizedDescription);
];
[operation start];
我有回应:
"Result":"fail","Message":"unexpected end of JSON input","Data":null
我的要求是通过 POST 在变量“数据”中发送登录名和密码,但是如果我在这里通过字典中的文本发送请求,如何在我的服务器上发送此变量?
【问题讨论】:
您要上传到哪个服务器?如果您需要像普通 Web 表单那样发送 POST,请查看***.com/questions/3508338/… 如果您已经确定要使用 AFNetworking 2.0,如your other question would suggest,那么我建议您在下面接受 user3200708 的回答(这样他就会因帮助您和您而获得“声誉”)将关闭这个问题)。你真的不应该同时打开这么多(我数了四五个)重复的问题。 我需要在可变数据中发送数据,对此很抱歉 感谢您清理旧问题!我将在your other question 解决您的“变量数据”问题。在 cmets 中讨论多个问题是没有意义的! 【参考方案1】:NSDictionary *params = @@"email" : email,
@"password" : pass
;
NSString* HOST_URL = @"http://server.com:8080";
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager POST:HOST_URL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
// Enter what happens here if successsful.
failure:^(AFHTTPRequestOperation *operation, NSError *error)
// Enter what happens here if failure happens
【讨论】:
【参考方案2】:我知道了:
NSString *URLString = @"http://server.com:8080/login";
// login = @"user1@1q2w3e"; // user1@1q2w3e user3@frcity
// password = @"1q2w3e";
NSString* data = @"\"email\": \"user1@1q2w3e\" ,\"password\": \"1q2w3e\"";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
NSDictionary *params = @@"data" : data;
[manager POST:URLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
NSLog(@"JSON: %@", responseObject);
failure:^(AFHTTPRequestOperation *operation, NSError *error)
NSLog(@"Error: %@", error);
];
【讨论】:
***.com/questions/42573527/…以上是关于如何通过 POST 和 AFNetworking 以变量形式发送数据?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 AFNetworking 通过 Post 请求在服务器上发送 NSData?
如何使用数组作为标头和 AFNetworking 进行 POST
obj-c AFNetworking 2.0 POST 请求不起作用