NSURLConnection

#GET

// 0.请求路径
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://120.25.226.186:32812/login?username=%@&pwd=%@", username, pwd]];
    
    // 1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    
    // 2.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 3.解析服务器返回的数据(解析成字符串)
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        // 4.回到主线程
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            // 隐藏HUD
           //            [SVProgressHUD dismiss];
        }];
    }];

#POST

// 1.请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    
    // 2.创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 更改请求方法
    request.HTTPMethod = @"POST";
    // 设置请求体
    request.HTTPBody = [@"username=jack&pwd=jack" dataUsingEncoding:NSUTF8StringEncoding];
    // 设置超时(5秒后超时)
    request.timeoutInterval = 5;
    // 设置请求头
//    [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
    
    // 3.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) { // 比如请求超时
            NSLog(@"----请求失败");
        } else {
            NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];

#中文URL进行转码

// 0.请求路径
    NSString *urlStr = @"http://120.25.226.186:32812/login2?username=张三&pwd=123456";
    // 将中文URL进行转码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
request.HTTPBody = [@"username=张三&pwd=123456" dataUsingEncoding:NSUTF8StringEncoding];

转载于:https://my.oschina.net/jlongtian/blog/855826

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值