Если у вас есть глубокие знания RESTKit, ваш вход был бы весьма признателен. Спасибо.RestKit POST объект с параметрами NULL
Я пытаюсь отправить основной объект данных на сервер, он соединяется нормально, но сервер возвращает мне ответ, говорящий мне, что все параметры имеют значение NULL. Я знаю, что сервис работает, потому что я сделал тот же вызов службы с AFNetworking. К сожалению, у меня нет свободного доступа к серверу.
Вот что я сделал. Я создал объект ядра данных
PDRepresentative *representative = [NSEntityDescription insertNewObjectForEntityForName:@"PDRepresentative" inManagedObjectContext:context];
representative.address1 = @"address1";
representative.address2 = @"address2";
representative.city = @"city";
representative.city = @"city";
representative.company = @"company";
representative.country = @"country";
representative.email = @"email";
representative.fax = @"fax";
representative.firstName = @"TestFirst";
representative.lastName = @"lastName";
representative.middleName = @"middleName";
representative.phone = @"phone";
representative.phonePersonal = @"phonePersonal";
representative.repId = @"TEST_REP_ID";
representative.specialty = @"spec";
representative.state = @"state";
representative.zip = @"zip";
representative.event = event;
//Create the mapping
RKObjectMapping *postObjectMapping = [RKObjectMapping requestMapping];
[postObjectMapping addAttributeMappingsFromDictionary:@{@"repId":@"RepId",
@"firstName":@"First",
@"middleName": @"Middle",
@"lastName": @"Last",
@"address1": @"Address1",
@"address2": @"Address2",
@"city": @"City",
@"zip": @"Zip",
@"country": @"Country",
@"company": @"Company",
@"phone": @"Phone",
@"phonePersonal": @"PhonePersonal",
@"fax": @"Fax",
@"email": @"Email",
@"event.eventId": @"EventId",
@"specialty": @"Specialty"}];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:postObjectMapping
objectClass:[PDRepresentative class]
rootKeyPath:@"PostAddOrUpdateRep"
method:RKRequestMethodPOST];
[objectManager addRequestDescriptor:requestDescriptor];
//… assign the response descriptor
NSMutableURLRequest *request = [objectManager requestWithObject:representative method:RKRequestMethodPOST path:@"PostAddOrUpdateRep" parameters:nil];
RKObjectRequestOperation *operation = [objectManager objectRequestOperationWithRequest:request
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
NSLog(@"http body %@", test);
NSLog(@"error %@", error);
PDResponse *response = mappingResult.firstObject;
response = [response isKindOfClass:[PDResponse class]] ? response : nil;
TRACE_LOG(@"%@", response);
}
failure:^(RKObjectRequestOperation *operation, NSError *error){
NSLog(@"operation %@, error %@", operation, error);
}];
[objectManager enqueueObjectRequestOperation:operation];
Я использовал этот метод размещения объектов, а не с помощью postObject: путь: параметры: успех: неудача, потому что это было назначение целевого объекта, чтобы быть таким же, как объект запроса, но это будет вызывать ошибку, потому что объект ответа полностью отличается от того, что отправляется. Он будет вызывать RKMapperOperation addError. Он говорил что-то по очереди, он ожидал класс объекта запроса, но получил класс объекта ответа.
Что-то еще отметить
Если я бегу это после того, как я получаем запрос
// check the http body
NSDictionary *test = [NSJSONSerialization JSONObjectWithData:request.HTTPBody
options:kNilOptions
error:&error];
NSLog(@"http body %@", test);
NSLog(@"error %@", error);
Это дает мне следующий вывод
2014-01-07 20:15:43.626 xctest[65449:303] http body (null)
2014-01-07 20:15:43.627 xctest[65449:303] error Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x2a49940 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Еще одна вещь, чтобы отметить, я сделал некоторые испытания и заметил, что тело http было создано из следующего словаря
(lldb) po [objectParameters requestParameters]
{
"PostAddOrUpdateRep" = {
Address1 = address1;
Address2 = address2;
City = city;
Company = company;
Country = country;
Email = email;
EventId = EventId;
Fax = fax;
First = TestFirst;
Last = lastName;
Middle = middleName;
Phone = phone;
PhonePersonal = phonePersonal;
RepId = "TEST_REP_ID";
Specialty = spec;
Zip = zip;
};
}
Который не выглядит правильным. Я пошел вперед и изменил тело http, чтобы быть тем же самым, что и тело HTTP запроса, созданного AFNetworking, которое было должным образом десериализовано из NSJSONSerialization, и сервер все еще возвращает мне исключение, говорящее мне, что все параметры были NULL.
Вот код для работы AFNetworking код
AFHTTPClient *client = [RKObjectManager sharedManager].HTTPClient;
NSDictionary *parameters = @{
@"RepId": @"123",
@"First": @"Jack",
@"Middle": @"Q",
@"Last": @"Public",
@"Address1": @"sample string 5",
@"Address2": @"sample string 6",
@"City": @"sample string 7",
@"State": @"sample string 8",
@"Zip": @"sample string 9",
@"Country": @"sample string 10",
@"Company": @"sample string 11",
@"Phone": @"sample string 12",
@"PhonePersonal": @"sample string 13",
@"Fax": @"sample string 14",
@"Email": @"sample string 15",
@"Specialty": @"sample string 16",
@"EventId": @"EventId"
};
client.parameterEncoding = AFJSONParameterEncoding;
NSURLRequest *request = [client requestWithMethod:@"POST" path:@"PostAddOrUpdateRep" parameters:parameters];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
TRACE_LOG(@"%s \nResponseObject %@", __PRETTY_FUNCTION__, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
TRACE_LOG(@"Operation %@", operation);
TRACE_LOG(@"Error %@", error);
}];
[client enqueueHTTPRequestOperation:operation];
// check the http body
NSError *error = nil;
NSDictionary *test = [NSJSONSerialization JSONObjectWithData:request.HTTPBody
options:kNilOptions
error:&error];
NSLog(@"http body %@", test);
NSLog(@"error %@", error);
The console output
2014-01-07 20:24:16.370 xctest[65939:303] http body {
Address1 = "sample string 5";
Address2 = "sample string 6";
City = "sample string 7";
Company = "sample string 11";
Country = "sample string 10";
Email = "sample string 15";
EventId = EventId;
Fax = "sample string 14";
First = Jack;
Last = Public;
Middle = Q;
Phone = "sample string 12";
PhonePersonal = "sample string 13";
RepId = 123;
Specialty = "sample string 16";
State = "sample string 8";
Zip = "sample string 9";
}
2014-01-07 20:24:16.371 xctest[65939:303] error (null)
2014-01-07 20:24:16.373 xctest[65939:303] I restkit.network:RKObjectRequestOperation.m:180 POST 'http://192.168.xxx.xxx/PostAddOrUpdateRep/1'
2014-01-07 20:24:18.755 xctest[65939:303] I restkit.network:RKObjectRequestOperation.m:216 POST 'http://192.168.xxx.xxx/PostAddOrUpdateRep/1' (200 OK) [2.3812 s]
2014-01-07 20:24:24.473 xctest[65939:303] __20-[PMGRepTests test2]_block_invoke
ResponseObject {
Ex = "<null>";
Message = "";
Success = 1;
TransactionId = 1;
Value = {
Address1 = "sample string 5";
Address2 = "sample string 6";
City = "sample string 7";
Company = "sample string 11";
Country = "sample string 10";
Email = "sample string 15";
EventId = EventId;
Fax = "sample string 14";
First = Jack;
Last = Public;
Middle = Q;
Phone = "sample string 12";
PhonePersonal = "sample string 13";
RepId = 123;
Specialty = "sample string 16";
State = "sample string 8";
Zip = "sample string 9";
};
}
спасибо. Вы были правы в обоих пунктах. – Biclops