Iphone 如何使用NSURLRequest在Http请求中发送json数据
我是objective-c的新手,从最近开始,我在请求/响应方面投入了大量精力。我有一个工作示例,可以调用url(通过HTTPGET)并解析返回的json 下面是这方面的工作示例Iphone 如何使用NSURLRequest在Http请求中发送json数据,iphone,objective-c,cocoa-touch,json,nsurlrequest,Iphone,Objective C,Cocoa Touch,Json,Nsurlrequest,我是objective-c的新手,从最近开始,我在请求/响应方面投入了大量精力。我有一个工作示例,可以调用url(通过HTTPGET)并解析返回的json 下面是这方面的工作示例 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; } - (void)connection:(NSURLConn
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
- (void)viewDidLoad
{
[self searchForStuff:@"iPhone"];
}
-(void)searchForStuff:(NSString *)text
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whatever.com/json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
我的第一个问题是——这种方法会扩大吗?或者这不是异步的(意味着我在应用程序等待响应时阻塞UI线程)
我的第二个问题是-我如何修改请求部分,以执行POST而不是GET?这样简单地修改HttpMethod吗
[request setHTTPMethod:@"POST"];
最后—如何将一组json数据作为简单字符串添加到本文中(例如)
提前谢谢我建议使用
ASIHTTPRequest是一个易于使用的
围绕CFNetwork API的包装器
使一些更乏味的方面
与web服务器通信的方法
更容易的。它是用Objective-C编写的
并且可以在Mac OS X和iPhone中使用
应用程序
它适合执行基本HTTP
请求并与之交互
基于REST的服务(GET/POST/PUT)
/删除)。包括
ASIFormDataRequest子类使其
易于提交POST数据和文件
使用多部分/表单数据
请注意,原作者已停止此项目。有关原因和备选方案,请参见以下帖子: 就我个人而言,我是的忠实粉丝,以下是我所做的(请注意,对于key=question..e.{:question=>{dictionary}},进入我服务器的JSON需要是一个具有一个值的字典(另一个字典): 然后由以下人员处理接收数据:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:@"question"];
这不是100%清楚,需要重新阅读,但一切都应该在这里让你开始。据我所知,这是异步的。在进行这些调用时,我的UI未被锁定。希望能有所帮助。这是一篇使用
它解释了如何将嵌套数据序列化为JSON并将数据附加到HTTP POST请求 你们中的大多数人现在已经知道了这一点,但我正在发布这一点,以防万一,你们中的一些人仍然在iOS6+中使用JSON 在iOS6和更高版本中,我们有一个快速且不依赖于包含“外部”库的方法
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
这就是iOS6和更高版本现在可以高效解析JSON的方式。SBJson的使用也是ARC之前的实现,如果您在ARC环境中工作,也会带来这些问题
我希望这有帮助 这里有一个使用NSURLConnection+sendAsynchronousRequest:(10.7+,iOS 5+)的更新示例,“Post”请求与接受的答案相同,为了清晰起见,此处省略:
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:@"http://www.myserver.com/api/api.php?request=%@", @"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(@"%@", responseString);
}
}
}];
我为此挣扎了一段时间。在服务器上运行PHP。此代码将发布一个json并从服务器获取json回复
NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"Server Response (we want to see a 200 return code) %@",response);
NSLog(@"dictionary %@",dictionary);
}
else if ([data length] == 0 && error == nil){
NSLog(@"no data returned");
//no data, but tried
}
else if (error != nil)
{
NSLog(@"there was a download error");
//couldn't download
}
}];
因为我对Mike G关于代码现代化的回答的编辑以3比2的比例被拒绝 这篇编辑文章的目的是针对文章的作者,不做任何修改 感觉就像编辑一样。它应该写成评论或评论 答复 我在这里重新发布我的编辑作为一个单独的答案。正如Rob以15票赞成的评论所示,此编辑删除了与
NSJSONSerialization
的JSONRepresentation
依赖关系
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"];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[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];
}
然后由以下人员处理接收数据:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:@"question"];
您可以尝试将此代码用于发送json字符串
除了这一行[dict objectForKey:@“user_question”],nil];--您的样品中未声明dict。这只是一本简单的字典还是什么特别的东西?很抱歉。是的,“dict”只是我从iOS用户文档中加载的一个简单字典。这是使用
NSDictionary
实例方法JSONRepresentation
。我可能建议我使用NSJSONSerialization
类方法dataWithJSONObject
,而不是。通过类似[[NSNumber numberWithUnsignedInt:requestData.length]stringValue]的NSNumber将nsuiger转换为NSString更有效
@MikeG修复了代码示例中一个长期存在且至今未被注意到的错误。抱歉,编辑您的帖子;)这里有一个教程:这个问题是关于POSTno的,问题的第一部分是关于异步性的,这里没有回答这个问题的答案。为下一票欢呼。content type=“application/x-www-form-urlencoded”成功了。谢谢你的回答。我在案例中使用了“application/json”
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php¶m=%@",jsonString];