在和sever後臺交互的過程中、有時候、他們需要我們iOS開發者以“application/json”形式上傳。 ...
在和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); }