发送json数据给服务器

来源:互联网 发布:js异或运算符 编辑:程序博客网 时间:2024/05/17 06:07
发送JSON数据给服务器的步骤:(1)一定要使用POST请求(2)设置请求头(3)设置JSON数据为请求体代码示例:  #import "YYViewController.h"  @interface YYViewController ()  @end  @implementation YYViewController  - (void)viewDidLoad {     [super viewDidLoad]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {             1.创建请求     NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/order"];     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];     request.HTTPMethod = @"POST";     // 2.设置请求头     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type”];     // 3.设置请求体     NSDictionary *json = @{                            @"order_id" : @"123",                            @"user_id" : @"789",                            @"shop" : @"Toll"                            };     // NSData --> NSDictionary     // NSDictionary --> NSData     NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];     request.HTTPBody = data;    // 4.发送请求     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        NSLog(@"%d", data.length);  }]; } @end
0 0