iOS发送请求

NSURLSession GET
NSURL *url = [NSURL URLWithString:@"http://c.m.163.com/nc/article/list/T1348649145984/0-10.html"];
    //创建请求 并:设置缓存策略为每次都从网络加载 超时时间30秒
    NSURLRequest *request  = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    //1.创建NSURLSession对象(可以获取单例对象),采用苹果提供的共享session
    NSURLSession *sharedSection = [NSURLSession sharedSession];
    //2.根据NSURLSession对象创建一个Task
    //方法参数说明
    /*
     注意:该block是在子线程中调用的,如果拿到数据之后要做一些UI刷新操作,那么需要回到主线程刷新
     第一个参数:需要发送的请求对象
     block:当请求结束拿到服务器响应的数据时调用block
     block-NSData:该请求的响应体
     block-NSURLResponse:存放本次请求的响应信息,响应头,真实类型为NSHTTPURLResponse
     block-NSErroe:请求错误信息
     */
    NSURLSessionDataTask *dataTash = [sharedSection dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@",dict);
    }];
    [dataTash resume];
NSURLSession POST
NSURL *url = [NSURL URLWithString:@"http://c.m.163.com/nc/article/list/T1348649145984/0-10.html"];
    //创建请求 并:设置缓存策略为每次都从网络加载 超时时间30秒
//    NSURLRequest *getRequest  = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:url];
    postRequest.HTTPMethod = @"POST";
    postRequest.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
    //1.创建NSURLSession对象(可以获取单例对象),采用苹果提供的共享session
    NSURLSession *sharedSection = [NSURLSession sharedSession];
    //2.根据NSURLSession对象创建一个Task
    //方法参数说明
    /*
     注意:该block是在子线程中调用的,如果拿到数据之后要做一些UI刷新操作,那么需要回到主线程刷新
     第一个参数:需要发送的请求对象
     block:当请求结束拿到服务器响应的数据时调用block
     block-NSData:该请求的响应体
     block-NSURLResponse:存放本次请求的响应信息,响应头,真实类型为NSHTTPURLResponse
     block-NSErroe:请求错误信息
     */
    NSURLSessionDataTask *dataTash = [sharedSection dataTaskWithRequest:postRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@",dict);
    }];
    [dataTash resume];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容