91 POST JSON 多值参数 获得mineType

来源:互联网 发布:学生围巾 知乎 编辑:程序博客网 时间:2024/06/03 14:01
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);
0 0