三步走:
1.使用POST请求
2.设置请求头
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
3.设置JSON数据为请求体
//
// ViewController.m
// IOS_0130_发送JSON给服务器
//
// Created by ma c on 16/1/30.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import "MBProgressHUD+MJ.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor];
// Do any additional setup after loading the view, typically from a nib.
} - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//发送JSON数据给服务器
//[self sendJSON];
//多值参数
[self multiValueParameter]; }
///多值参数
- (void)multiValueParameter
{
//1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/weather"];
//2.请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.请求方法
request.HTTPMethod = @"POST";
//4.设置请求体
NSMutableString *param = [NSMutableString string];
[param appendString:@"place=BeiJing&place=TianJin&place=AnHui"];
// [param appendString:@"&place=TianJin"];
// [param appendString:@"&place=AnHui"];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding]; //5.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (data == nil || connectionError) return;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}
else{
NSArray *weathers = dict[@"weathers"];
NSLog(@"%@",weathers);
}
}];
}
///发送JSON数据给服务器
- (void)sendJSON
{
//1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"];
//2.请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.请求方法
request.HTTPMethod = @"POST";
//4.设置请求体
//创建一个描述订单信息的JSON数据
NSDictionary *dict = @{
@"shop_id" : @"",
@"shop_name" : @"bowen",
@"user_id" : @""
};
NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = json; //5.设置请求头:这次请求体的数据不再是参数,而是JSON数据 value:MIMEType
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; //6.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (data == nil || connectionError) return;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}
else{
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}];
}
@end