oc调用rest api
无需其他类库
1: - (IBAction)callapi:(id)sender {
2: NSURL *url=[NSURL URLWithString:@"http://..."];
3: NSURLRequest *request=[NSURLRequest requestWithURL:url];
4: [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
5: //json
6: NSDictionary *r=[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
7: int cnt=[r count];
8: NSLog(@"%d",cnt);
9: [self resultlbl].text=[NSString stringWithFormat:@"%d",cnt];
10:
11: //string
12: //NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
13: //NSLog(str);
14: //[self resultlbl].text=r[0][0];
15: }];
16: }
post
1: - (IBAction)postsend:(id)sender {
2: NSURL *url = [NSURL URLWithString:@"http://...."];
3: NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
4: [rq setHTTPMethod:@"POST"];
5:
6: NSData *jsonData = [@"{ \"参数名\": 数值,\"参数名\":\"字符\"... }" dataUsingEncoding:NSUTF8StringEncoding];
7: [rq setHTTPBody:jsonData];
8:
9: [rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
10: [rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
11:
12: [NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
13: //code
14: NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
15: NSLog(str);
16: }];
17:
18: }