oc调用rest api
2015-05-29 10:34
302 查看
无需其他类库
post
- (IBAction)callapi:(id)sender {
NSURL *url=[NSURL URLWithString:@"http://..."];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//json
NSDictionary *r=[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
int cnt=[r count];
NSLog(@"%d",cnt);
[self resultlbl].text=[NSString stringWithFormat:@"%d",cnt];
//string
//NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(str);
//[self resultlbl].text=r[0][0];
}];
}
post
- (IBAction)postsend:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://...."];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSData *jsonData = [@"{ \"参数名\": 数值,\"参数名\":\"字符\"...}" dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//code
NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(str);
}];
}
相关文章推荐
- 静态路由的配置
- iOS动画
- Git学习笔记1
- fsm in ironic
- 引导界面(二)使用ViewPager实现欢迎引导页面
- #21 Merge Two Sorted Lists
- 第三章30题
- 杭电oj 3361
- HTML标签要用推荐标准写法去写,否则浏览器兼容性很差
- 引导界面(四)仿人人网V5.9.2最新版引导界面
- MT9V034 全局快门体验总结
- [struts.convention.package.locators] 与 [struts.convention.action.packages] 的区别
- 一起学android之自定义控件显示点赞用户并通过用户名称进入该用户主页的功能 (40)
- 环境安装
- @responsebody注解
- struts2遍历map集合
- 环境搭建二 secureCRT配置
- linux配置IP的方法
- jQuery实现返回顶部效果的方法
- 引导界面(三)仿微信引导界面以及动画效果