ios网络学习------2 用非代理方法实现同步post请求

#pragma mark  - 这是私有方法,尽量不要再方法中直接使用属性,由于一般来说属性都是和界面关联的,我们能够通过參数的方式来使用属性
#pragma mark post登录方法
-(void)loginWithPostWithName:(NSString *)userName pwd:(NSString *)pwd
{
    //1确定地址NSURL
    NSString *urlString = [NSString stringWithFormat:@"www.baidu.com"];
    NSURL *url = [NSURL URLWithString:urlString];
    
    //2建立请求NSMutableURLRequest(post须要用这个)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //网络訪问超时时间
    [request setTimeoutInterval:2.0f];
    //1)post请求方式,网络请求默认是get方法。所以假设我们用post请求,必须声明请求方式。
    [request setHTTPMethod:@"POST"];
    //2)post请求的数据体,post请求中数据体时,假设有中文。不须要转换。由于ataUsingEncoding方法已经实现了转码。
    NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@", userName, pwd];
    //将nstring转换成nsdata
    NSData *body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"body data %@", body);
    [request setHTTPBody:body];
    
//    //3建立并启动连接NSRULConnection
//    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
//    [conn start];  //启动连接,这是网络请求已经发生了。这是一个异步连接请求,,请求发送出去以后,就交由代理处理。
    
    //3不用代理的同步请求,
    NSURLResponse *response = nil;
    NSError *error = nil;
    //第二。三个參数是指针的指针,全部要用取址符。这种方法是同步方法。同步操作没有完毕。后面的代码不会运行。
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //同步訪问的数据的兴许处理
    if (data != nil) {  //接受到数据,表示工作正常
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
    }else if(data == nil && error != nil)    //没有接受到数据,可是error为nil。。

表示接受到空数据。 { NSLog(@"接受到空数据"); }else{ NSLog(@"%@", error.localizedDescription); //请求出错。 } // //服务器通知准备,准备中转数据 // self.serverData = [NSMutableData data]; }


【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10858067.html