首页 > 移动平台 > 详细

IOS-网络发送JSON数据给服务器

时间:2016-01-30 22:41:12      阅读:254      评论:0      收藏:0      [点我收藏+]

 

三步走:

1.使用POST请求

2.设置请求头

   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

3.设置JSON数据为请求体

 

 1 //
 2 //  ViewController.m
 3 //  IOS_0130_发送JSON给服务器
 4 //
 5 //  Created by ma c on 16/1/30.
 6 //  Copyright © 2016年 博文科技. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 #import "MBProgressHUD+MJ.h"
11 
12 @interface ViewController ()
13 
14 @end
15 
16 @implementation ViewController
17 
18 - (void)viewDidLoad {
19     [super viewDidLoad];
20     self.view.backgroundColor = [UIColor cyanColor];
21     // Do any additional setup after loading the view, typically from a nib.
22 }
23 
24 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
25 {
26     //1.URL
27     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"];
28     //2.请求
29     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
30     //3.请求方法
31     request.HTTPMethod = @"POST";
32     //4.设置请求体
33     //创建一个描述订单信息的JSON数据
34     NSDictionary *dict = @{
35                            @"shop_id" : @"123456",
36                            @"shop_name" : @"bowen",
37                            @"user_id" : @"2012110606"
38                            };
39     NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
40     request.HTTPBody = json;
41     
42     //5.设置请求头:这次请求体的数据不再是参数,而是JSON数据 value:MIMEType
43     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
44     
45     //6.发送请求
46     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
47         if (data == nil || connectionError)  return;
48         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
49         NSString *error = dict[@"error"];
50         if (error) {
51             [MBProgressHUD showError:error];
52         }
53         else{
54             NSString *success = dict[@"success"];
55             [MBProgressHUD showSuccess:success];
56         }
57     }];
58 }
59 @end

 

IOS-网络发送JSON数据给服务器

原文:http://www.cnblogs.com/oc-bowen/p/5172205.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!