iOS开发往服务器Post一个json数据

有时候需要往服务器Post一个json数据。

参数

参数可以被自动序列号。前提是要是iOS里面的数据类型,比如NSDictionary,NSArray,NSNumber,NSString等。如果是自己的模型数组,可以自己写一个模型的ToString方法,网上似乎也有些库,不过自己写起来也不麻烦。
比如我传的是一个联系人数组。

@interface ContactModel : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *contact_phone;
@property (nonatomic, strong) NSString *created_at;

- (NSString *)modelToString;
@end

- (NSString *)modelToString{
    return [NSString stringWithFormat:@"{\"contact_phone\":\"%@\", \"name\":\"%@\", \"source\":1, \"created_at\":\"%@\"}",_contact_phone,_name,_created_at];
}
@end

然后往模型里面添加数组之前。先调用modelToString进行序列号就好。
参数里面可以直接使用数组。
比如

   NSMutableArray *array =  [ContactsHelper contactArray];
   NSDictionary *parmeters = @{@"user_id":@"2222",
                             @"contact":array
                             };

请求

使用原生的http请求。

-(void)request: (NSString*)httpUrl withHttpArg: (NSDictionary*)parameters{
    NSURL *url = [NSURL URLWithString: httpUrl];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"POST"];
    if (parameters) {
        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
            [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        }
        [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
    }
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"HttpResponseCode:%ld", responseCode);
                                   NSLog(@"HttpResponseBody %@",responseString);
                                   NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                   NSDictionary *dicjson = (NSDictionary *)json;
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       //刷新UI
                                   });                               }
                           }];
}

使用AFNetWorking。

NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString: parameters:parmeters error:nil];
  [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"HttpResponseCode:%ld", responseCode);
                                   NSLog(@"HttpResponseBody %@",responseString);
                                   NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                   NSDictionary *dicjson = (NSDictionary *)json;
                                   NSLog(@"%@",dicjson);
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       //刷新UI
                                   });

                               }
                           }];

推荐使用AFNetworking。自己的话还需要加一些其它的设置,具体我还要研究。

博客地址 iseedog

你可能感兴趣的:(iOS)