//
// JLViewController.m
// 02-PostJSON
//
// Created by Mac on 15-4-11.
// Copyright (c) 2015年 vxinyou. All rights reserved.
//
#import "JLViewController.h"
#import "JLPerson.h"
@interface JLViewController ()
@end
@implementation JLViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
/**
* 上传json数据到服务器
*/
- (void)postJson{
// 创建URL
NSURL *url = [NSURL URLWithString:@"请填写url地址"];
// 创建Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
// 设置请求方式
request.HTTPMethod = @"POST";
// 在iOS中JSON就是NSDictionary/NSArray
// 使用NSDictionary & NSArray可以各种灵活组合
NSDictionary *dict = @{
@"name": @"zhangsan",
@"age" : @18,
@"book" : @[@"iOS开发上",@"iOS开发下"],
@"zoom" : @1
};
NSDictionary *dict1 = @{
@"name": @"lisi",
@"age" : @24,
@"book" : @[@"iOS 7",@"iOS 6"],
@"zoom" : @2
};
NSArray *array = @[dict, dict1];
// 把字典转换成二进制数据流, 序列化
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
// 发送异步请求,并获取结果
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
}];
}
/**
* 模型对象转字典,字典转json,json上传到服务器
*/
- (void)postObj{
// 创建URL
NSURL *url = [NSURL URLWithString:@"请填写url地址"];
// 创建Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
// 设置请求方式
request.HTTPMethod = @"POST";
JLPerson *person = [[JLPerson alloc] init];
person.name = @"zhangsan";
person.age = 34;
// 使用KVC将模型对象转成字典,数组中不一定要包含全部的模型属性。
id obj = [person dictionaryWithValuesForKeys:@[@"name", @"age"]];
// 把字典转换成二进制数据流, 序列化
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:obj options:0 error:NULL];
// 发送异步请求,并获取结果
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
}];
}
@end
//
// JLPerson.h
// 02-PostJSON
//
// Created by Mac on 15-4-11.
// Copyright (c) 2015年 vxinyou. All rights reserved.
//
#import
@interface JLPerson : NSObject
@property (nonatomic, copy)NSString *name;
@property (nonatomic, assign)NSInteger age;
@end
//
// JLPerson.m
// 02-PostJSON
//
// Created by Mac on 15-4-11.
// Copyright (c) 2015年 vxinyou. All rights reserved.
//
#import "JLPerson.h"
@implementation JLPerson
@end