Запрос AFNetworking и POST
Я получаю этот ответ в error.userInfo, делая запрос POST от AFNetworking
.
Может ли кто-нибудь сказать, что мне не хватает ничего очевидного или что-то нужно исправить на моем сервере?
Запрос с ошибкой: Ошибка домена = AFNetworkingErrorDomain Код = -1016 "Предполагаемый тип контента {( " Текст /JSON ", " Применение /JSON ", " text/javascript ")}, получил текст /html " UserInfo = 0x6d7a730 {NSLocalizedRecoverySuggestion = индексный тест, AFNetworkingOperationFailingURLResponseErrorKey =, NSErrorFailingURLKey = http://54.245.14.201/, NSLocalizedDescription = ожидаемый тип контента {( "Текст/JSON ", " Применение /JSON ", " text/javascript")}, получил текст /html, AFNetworkingOperationFailingURLRequestErrorKey = http://54.245.14.201/ " > }, { AFNetworkingOperationFailingURLRequestErrorKey =" http://54.245.14.201/ " > "; AFNetworkingOperationFailingURLResponseErrorKey = "; NSErrorFailingURLKey =" http://54.245.14.201/ "; NSLocalizedDescription =" Ожидаемый тип контента {(\n \ "text/json\", \n \ "application/json\", \n
\ "text/javascript \" \n)}, получил текст /html "; NSLocalizedRecoverySuggestion =" индексный тест"; }
И я использую этот код;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"Ans", @"name",
@"29", @"age",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Success");
NSLog(@"%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
NSLog(@"Failure");
}];
[operation start];
[operation waitUntilFinished];
Ответы
Ответ 1
По умолчанию AFJSONRequestOperation
принимает только типы контента "text/json", "application/json" или "text/javascript" с сервера, но вы получаете "text/html".
Исправление на сервере было бы лучше, но вы также можете добавить тип контента "text/html" в качестве приемлемого в вашем приложении:
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
Это сработало для меня, надеюсь, это поможет!
Ответ 2
Вы отправили этот запрос POST на AFHTTPClient
? Если это так, вам нужно установить для него класс работы:
AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:8080"]];
// ...
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"];
// ...
// EDIT: Use AFHTTPClient POST method
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"Ans", @"name",
@"29", @"age", nil];
// POST, and for GET request, you need to use |-getPath:parameters:success:failure:|
[client postPath:@"/"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"RESPONSE: %@", responseObject);
// ...
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (error)
NSLog(@"%@", [error localizedDescription]);
// ...
}
Ответ 3
Задайте свои значения в этом коде и проверьте, работает ли он для вас.
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:kBASEURL]];
NSString *_path = [NSString stringWithFormat:@"groups/"];
_path = [_path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%s %@",__PRETTY_FUNCTION__,_path);
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
path:_path
parameters:postParams];
[httpClient release];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if ([JSON isKindOfClass:[NSArray class]] || [JSON isKindOfClass:[NSDictionary class]]) {
completed(JSON);
}
else {
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@" response %@ \n error %@ \n JSON %@",response,error,JSON);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
errored(error);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];