iOS application/json上傳檔案等,iosjson
在和sever後台互動的過程中、有時候、他們需要我們iOS開發人員以“application/json”形式上傳。
NSString *accessUrl = [NSString stringWithFormat:@"%@/xxx",@"https://www.xxxxx.com:xxxx"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:accessUrl]]; request.HTTPMethod = @"POST"; //佈建要求頭 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; //佈建要求體 NSMutableData *body = [NSMutableData data]; [body appendData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSHTTPURLResponse* urlResponse = nil; NSError *error = [[NSError alloc] init]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; if (result == nil) { NSLog(@"json解析失敗!"); } else { NSData *jsonData = [result dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err]; if(err) { NSLog(@"json解析失敗:%@",err); } success(dic); }