您的位置:首页 > 其它

oc调用rest api

2015-05-29 10:34 302 查看
无需其他类库

- (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);   


}];




}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: