如何获取HTTP post请求获取JSON对象以响应iPhone应用程序? [英] How do I make HTTP post request for getting JSON object in response for iPhone application?

查看:131
本文介绍了如何获取HTTP post请求获取JSON对象以响应iPhone应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务器上运行的Web服务以XML格式或JSON格式返回数据。
我想申请JSON格式但是使用HTTP Post方法。

I've a web service running on server which return data either in XML format or JSON format. I wanted to request a JSON format but using HTTP Post method.

任何帮助都非常感谢。

提前感谢。

推荐答案

这是适用于JSON发布请求的代码,
使用TouchJSON框架解析JSON,谢谢'schwa'。

This is the code which work for JSON post request, TouchJSON Framework is used for parsing the JSON, thanks 'schwa'.

NSArray *keys = [NSArray arrayWithObjects:@"username", @"password", @"preference", @"uid", nil];
NSArray *objects = [NSArray arrayWithObjects:@"accuser", @"accpass", @"abc_region", @"100", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSURL *theURL = [NSURL URLWithString:@"http://url.com/request.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:@"POST"];

[theRequest setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"];
NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
NSLog(@"%@", theBodyString);
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"%@", theBodyData);
[theRequest setHTTPBody:theBodyData];

NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(theResponseString);
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString];
NSLog(@"%@", theResponseDictionary);
NSString *theGreeting = [theResponseDictionary objectForKey:@"greeting"];
[self setValue:theGreeting forKey:@"greeting"];

这篇关于如何获取HTTP post请求获取JSON对象以响应iPhone应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆