更新:发现以下JSON部分可用于PUT / POST,但不适用于GET / HEAD / DELETE
经过一番争执,在SO的帮助下,我得到了一些工作,我想把它留作纪念。最后,AFNetworking-2给我留下了非常深刻的印象。它是如此简单,我一直努力使它变得比原来更难。给定一个
jsonDict返回要发送的json数据包的方法,我创建了以下代码:
- (void) submitAuthenticatedRest_PUT{ // it all starts with a manager AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // in my case, I'm in prototype mode, I own the network being used currently, // so I can use a self generated cert key, and the following line allows me to use that manager.securityPolicy.allowInvalidCertificates = YES; // Make sure we a JSON serialization policy, not sure what the default is manager.requestSerializer = [AFJSonRequestSerializer serializer]; // No matter the serializer, they all inherit a battery of header setting APIs // Here we do Basic Auth, never do this outside of HTTPS [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"basic_auth_username" password:@"basic_auth_password"]; // Now we can just PUT it to our target URL (note the https). // This will return immediately, when the transaction has finished, // one of either the success or failure blocks will fire [manager PUT: @"https://101.202.303.404:5555/rest/path" parameters: [self jsonDict] success:^(AFHTTPRequestOperation *operation, id responseObject){ NSLog(@"Submit response data: %@", responseObject);} // success callback block failure:^(AFHTTPRequestOperation *operation, NSError *error){ NSLog(@"Error: %@", error);} // failure callback block ];}3条设置语句,然后发送2条消息,这真的很容易。
编辑/添加:这是一个@jsonDict实现示例:
- (NSMutableDictionary*) jsonDict{ NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; result[@"serial_id"] = self.serialID; result[@"latitude"] = [NSNumber numberWithDouble: self.location.latitude]; result[@"longitude"] = [NSNumber numberWithDouble: self.location.longitude]; result[@"name"] = self.name; if ([self hasPhoto]) { result[@"photo-jpeg"] = [UIImageJPEGRepresentation(self.photo, 0.5) base64EnpredStringWithOptions: NSDatabase64Encoding76CharacterLineLength];}return result;}
它应该只返回带有字符串键和简单对象作为值(NSNumber,NSString,NSArray(我认为)等)的字典。JSON编码器将为您完成其余工作。



