zoukankan      html  css  js  c++  java
  • NSURLSession实践(结合POST和GET请求JSON和XML数据)

    GET方法解析JSON数据,使用NSJSONSerialization

     1     NSString *appkey = @"bf1d95bd730f031fb019ba80ffabb89d";
     2     NSString *baseURL = @"http://op.juhe.cn/onebox/weather/query";
     3     NSString *url = [baseURL stringByAppendingString:[NSString stringWithFormat:@"?cityname=%@&dtype=&key=%@", @"上海", appkey]];
     4     NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
     5     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
     6     request.HTTPMethod =@"GET";
     7     request.timeoutInterval = 20;
     8     request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
     9     
    10     NSURLSession *session = [NSURLSession sharedSession];
    11     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    12         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    13         NSLog(@"%@", [dict allKeys]);
    14     }];
    15     [task resume];

    POST方法解析JSON数据,使用NSJSONSerialization,其他参数和之前一样

     1     //设置请求体
     2     NSString *bodyStr = [NSString stringWithFormat:@"cityname=%@&dtype=&key=%@", @"上海", appkey];
     3     NSString *body = [bodyStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
     4     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseURL]];
     5     request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
     6     request.HTTPMethod =@"POST";
     7     request.timeoutInterval = 20;
     8     request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
     9     
    10     NSURLSession *session = [NSURLSession sharedSession];
    11     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    12         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    13         NSLog(@"%@", [dict allKeys]);
    14     }];
    15     [task resume];
  • 相关阅读:
    C Pointer-to-Function 与 C++ Pointer-to-MemberFunction 的区别
    selenium-webdriver 简单教程
    关于元素不在窗口时如何找到元素
    python-ConfigParser模块【读写配置文件】
    Python定位SVG元素
    Selenium自动化测试Python三:WebDriver进阶
    selenium之 定位以及切换frame(iframe)
    webdriver 的三种等待方式
    Selenium2+python自动化38-显式等待(WebDriverWait)
    selenium webdriver python 元素操作
  • 原文地址:https://www.cnblogs.com/xiayao/p/5265672.html
Copyright © 2011-2022 走看看