美文网首页
iOS网络编程HTTP解决方案-NSURLConnection-

iOS网络编程HTTP解决方案-NSURLConnection-

作者: solozyx | 来源:发表于2016-08-05 16:47 被阅读0次

    GET方法:

    - (void)get{
        NSString *urlStr = @"http://www.jianshu.com/users/iOS程序员";
        // 将中文URL进行转码
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[[NSOperationQueue alloc] init]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                    // 解析服务器返回的数据(解析成字符串)
                                    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                    NSLog(@"%@", string);
                                }];
    }
    

    POST方法:

    - (void)post{
        NSString *urlStr = @"http://www.jianshu.com/users/login";
        NSURL *url = [NSURL URLWithString:urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
    
        // 百分号转码
        request.HTTPBody = [@"username=iOS程序员&pwd=密码" dataUsingEncoding:NSUTF8StringEncoding];
        
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[[NSOperationQueue alloc] init]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                    // 解析服务器返回的数据(解析成字符串)
                                    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                    NSLog(@"%@", string);
                                }];
    }
    

    相关文章

      网友评论

          本文标题:iOS网络编程HTTP解决方案-NSURLConnection-

          本文链接:https://www.haomeiwen.com/subject/muohsttx.html