ios综合挡程序员

iOS 网络访问 - NSURLConnection

2016-03-30  本文已影响303人  苏xiao孬

iOS 网络访问

NSURLConnection

    NSURL *url = [NSURL     NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 需要修改请求头或者请求体的时候,需要的是 mutable URL request
    NSMutableURLRequest *requestM = [[NSMutableURLRequest alloc] initWithURL:url];
    [requestM setValue:@"iPhone AppleWebKit" forHTTPHeaderField:@"User_Agent"];
    
    __weak typeof(self) weakSelf = self;
    // requestM 打开的才是移动端的网页
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil && data.length > 0) {
            NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [weakSelf.webView loadHTMLString:html baseURL:url];
        }
    }];

代码其实挺简单的,而且 NSURLConnection 已经 9.0 弃用了,如果还有想要尝试的童鞋还是可以看看的,毕竟是苹果最早处理网络访问的方法。
一般 connection 都会异步发送请求,但是也有同步的时候,比如断点续传,下载文件之前需要知道上次下载文件大小,就可以同步发送请求,而且可以发送 HEAD 请求。
HEAD 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/videos.zip"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // HEAD 请求不会返回响应体,只是返回响应头,可以查看数据大小
    request.HTTPMethod = @"HEAD";
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
    NSLog(@"HEAD response head -- %zd", response.expectedContentLength);
    NSLog(@"HEAD response body -- %zd", data.length);
P.S.(Postscript)

GET 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php?username=username+&password=pwd"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil && data.length > 0) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"%@", dict);
        } else {
            NSLog(@"%@", connectionError);
        }
    }];

POST 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 默认是通过 GET 发送请求
    request.HTTPMethod = @"POST";
    NSString *requestBodyString = @"username=username&password=pwd";
    NSData *requestBody = [requestBodyString dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBody;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil && data.length > 0) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"%@", dict);
        } else {
            NSLog(@"%@", connectionError);
        }
    }];
上一篇 下一篇

猜你喜欢

热点阅读