栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用NSURLRequest在Http请求中发送json数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用NSURLRequest在Http请求中发送json数据

这是我的工作(请注意,发送到我的服务器的JSON必须是一个字典,其中包含key = question..ie {:question =>
{dictionary}}}的一个值(另一个字典)):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];NSString *jsonRequest = [jsonDict JSONRepresentation];NSLog(@"jsonRequest is %@", jsonRequest);NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];[request setHTTPMethod:@"POST"];[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];[request setHTTPBody: requestData];NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];if (connection) { receivedData = [[NSMutableData data] retain];}

然后,receivedData由以下方式处理:

NSString *jsonString = [[NSString alloc] initWithdata:data encoding:NSUTF8StringEncoding];NSDictionary *jsonDict = [jsonString JSONValue];NSDictionary *question = [jsonDict objectForKey:@"question"];

这不是100%清楚的,需要重新阅读,但是所有内容都应该在这里,以帮助您入门。据我所知,这是异步的。进行这些调用时,我的UI未被锁定。希望有帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449164.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号