发送json到服务器
1,如果发送JSON数据,比如商城下单的时候发送下单信息给服务器,则必须在请求头中说明数据类型
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/order"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSDictionary *orderInfo = @{
@"shop_id":@"12341",
@"shop_name":@"zhang",
@"user_id":@"danfeng"
};
NSData *data01 = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = data01;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@",data);
if(data == nil || connectionError) return ;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
NSString *success = dict[@"success"];
if(error){
NSLog(@"%@",error);
}else{
NSLog(@"%@",success );
}
}];
}
发送多值参数到服务器
2,多值参数,也就是一个参数中有多个值,直接拼接成字符串放进去即可:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/weather"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSMutableString *body = [NSMutableString string];
[body appendString:@"place=beijing"];
[body appendString:@"&place=shanghai"];
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(connectionError || data == nil){
NSLog(@"request failed");
}
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
NSString *weather = dict[@"weathers"];
if(error){
NSLog(@"%@",error);
}else if(weather){
NSLog(@"%@",weather);
}
}];
}