iOS网络开发—POST请求和GET请求

创建GET请求:

//    1.设置请求路径
    NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
    NSURL *url=[NSURL URLWithString:urlStr];
    
//    2.创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
//    3.发送请求

服务器:

 

创建POST请求:

    //2、设置请求路径
    NSURL *url = [NSURL  URLWithString:@"http://192.168.1.135:83/login"];
    //3、创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval=5.0;//设置请求超时为5秒
    
//    [request setHTTPMethod:@"POST"];
    request.HTTPMethod = @"POST";//设置请求方法POST
    
    //5、设置请求体
    NSString *param = @"username=admin&password=123";
    
    //把拼接后的字符串转换为data,设置请求体
    [request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
    
    //1、创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //6、根据会话对象创建请求任务Task(发送请求)
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    //8.解析数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                NSLog(@"%@",dict);
        
        if (error) {
            
//            NSLog(@"%@",error);
            NSLog(@"失败");
        }
        
        NSString *ss = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"结果是:%@",ss);
        
        
    }];
    
    [task resume];
    
}

服务器:

posted on 2016-08-09 15:44  在一起的浅蓝色  阅读(189)  评论(0编辑  收藏  举报

导航