iOS 给服务器发送Json数据demo

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //1.创建请求
    
    NSURL *url=[NSURL URLWithString:@"http://192.168.1.121:8090/"];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod=@"POST";
    //2.设置请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //3.设置请求体
    NSDictionary *dict=@{@"name":@"chen",@"sex":@"nan",@"shop":@"tool"};

    //NSData --->NSDictionary
    //NSDictionary-->>NSData
    NSData *data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    request.HTTPBody=data;
    //发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%ld",data.length);
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


你可能感兴趣的:(服务器,Json数据)