1>POST JSON
有时候服务器接收的是json数据,这个时候需要将json数据传给服务器:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/order"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *json = @{
@"order_id" : @"123",
@"user_id" : @"789",
@"shop" : @"Toll"
};
NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = data;
[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];
NSLog(@"%@", repsonse.MIMEType);