ios开发 将json格式数据上传服务器

看了一些大小牛的资料其实就3步

1.使用post 请求 ,因为get是不能上传的

2.设置请求类型 , 讲你的json数据上传

3.向服务器发送数据按照下面示例代码,就差不多了

 1     // 1.创建请求
 2     NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/order"];
 3     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 4     request.HTTPMethod = @"POST";
 5     
 6     // 2.设置请求类型
 7     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 8     
 9     // 3.上传json数据
10     NSDictionary *json = @{
11                            @"order_id" : @"1",
12                            @"user_id" : @"1",
13                            @"shop" : @"1"
14                            };
15     
16 //    NSData --> NSDictionary
17     // NSDictionary --> NSData
18     NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
19     request.HTTPBody = data;
20     
21     // 4.发送请求
22     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
23         NSLog(@"%d", data.length);
24     }];
posted @ 2016-05-09 13:02  刘明鑫l  阅读(441)  评论(0编辑  收藏  举报