How to sent data in variable via POST and AFNetworking?

强颜欢笑 提交于 2020-01-15 03:26:15

问题


I use this method:

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];

And I have response:

{"Result":"fail","Message":"unexpected end of JSON input","Data":null}

My requirements is to send login and password via POST in variable "data", but how can I sent this variable on my server if I send request via text in dictionary here?


回答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:


I got this:

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);
}];


来源:https://stackoverflow.com/questions/21151527/how-to-sent-data-in-variable-via-post-and-afnetworking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!