您的位置:首页 > Web前端 > JavaScript

91 POST JSON 多值参数 获得mineType

2015-09-06 00:47 676 查看
1>POST JSON
有时候服务器接收的是json数据,这个时候需要将json数据传给服务器:
- (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);
}];
}
需要注意的是POST JSON的Content-Length可以不用传(自己不传,系统会传)
而文件上传的时候Content-Type必须要传

如果仅仅是传一般参数例如username给服务器的时候,POST的是string的data


2>多值参数

有时候一个url的参数可以接收很多参数值,例如天气预报的可以传多个地名给服务器
服务器给据每个地名给出天气预报,例如place=南京&place=北京,这个时候服务器是用数组接收参数值!


3>获得一种文件的mineType(Content-Type)
// 给本地文件发送一个请求
NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
NSURLResponse *repsonse = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil];

// 得到mimeType
NSLog(@"%@", repsonse.MIMEType);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: