zoukankan      html  css  js  c++  java
  • 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: }
  • 相关阅读:
    dfs 与 剪枝
    杭电OJ1789、南阳OJ236(贪心法)解题报告
    多边形面积问题(hdoj2036)
    retain copy(浅复制) mutablecopy (深复制)
    IOS开发的目录结构
    UITableView 委托方法总结
    ios block
    UITableView 学习笔记
    iso socket基础2
    ios socket(基础demo)
  • 原文地址:https://www.cnblogs.com/czcz1024/p/4537895.html
Copyright © 2011-2022 走看看