同步请求与异步请求

@interface ViewController ()
@property (weak, nonatomic) IBOutletUITextField *usernameTextField;
@property (weak, nonatomic) IBOutletUITextField *passwordTextField;
@property (strong,nonatomic) NSMutableData *fullData;
@property (weak, nonatomic) IBOutletUIImageView *imageView;

@end

@implementation ViewController
//同步
- (
IBAction)loginBySync:(UIButton *)sender
{
   
//1、网络连接地址
   
NSString *strURL =@"http://192.168.191.4/usermanager/0.png";
   
NSURL *url = [NSURLURLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   
//2、建立请求对象
   
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
    request.
timeoutInterval = 1;
    request.
HTTPMethod = @"post";
   
   
NSString *strBody = [NSStringstringWithFormat:@"submit =1&username = %@&password =%@",self.usernameTextField.text,self.passwordTextField.text];
   
    request.
HTTPBody = [strBody dataUsingEncoding:NSUTF8StringEncoding];
   
   
//request.HTTPBody = [[NSData alloc]initWithBytes:[strBody UTF8String] length:strBody.length];
   
//3、建立连接,发送请求
   
NSURLResponse *response = nil;
   
NSError *error = nil;
   
NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:&response error:&error];
   
if (error ==nil)
    {
       
unsignedlong encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
       
NSString *str = [[NSStringalloc]initWithData:data encoding:encode];
       
NSLog(@"接收到数据:%@",str);
    }
   
else
    {
       
NSLog(@"连接出错%@",error);
   
    }
   
}
//异步
- (
IBAction)loginAsync:(UIButton *)sender
{
   
//1、网络连接地址
   
NSString *strURL =@"http://192.168.191.4/usermanager/0.png";
   
NSURL *url = [NSURLURLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   
//2、建立请求对象
   
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
    request.
timeoutInterval = 1;
    request.
HTTPMethod = @"post";
   
   
NSString *strBody = [NSStringstringWithFormat:@"submit =1&username = %@&password =%@",self.usernameTextField.text,self.passwordTextField.text];
   
    request.
HTTPBody = [strBody dataUsingEncoding:NSUTF8StringEncoding];
   
   
//request.HTTPBody = [[NSData alloc]initWithBytes:[strBody UTF8String] length:strBody.length];
   
//3、建立连接,发送请求
    [
NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
if (connectionError ==nil)
        {
           
unsignedlong encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
           
NSString *str = [[NSStringalloc]initWithData:data encoding:encode];
           
NSLog(@"接收到数据:%@",str);
        }
       
else
        {
           
NSLog(@"连接出错%@",connectionError);
           
        }
    }];
}

//get
- (
IBAction)LoginByget:(UIButton *)sender
{
   
//1、网络连接地址
   
self.fullData = [[NSMutableDataalloc]init];

   
NSString *strURL = [NSStringstringWithFormat:@"http://192.168.191.4/usermanager/login.php?username=%@&password=%@",self.usernameTextField.text,self.passwordTextField.text];
   
//NSString *strURL = [NSString stringWithFormat:@"http://192.168.191.4/usermanager/0.png";
   
NSURL *url = [NSURLURLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   
//2、建立请求对象
   
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
   
//3、建立连接,发送请求
   
NSURLConnection *conn = [NSURLConnectionconnectionWithRequest:request delegate:self];
    [conn
start];
   
}
//post
- (
IBAction)LoginBypost:(UIButton *)sender
{
   
   
self.fullData = [[NSMutableDataalloc]init];
   
//1、网络连接地址
   
NSString *strURL =@"http://192.168.191.4/usermanager/0.png";
   
NSURL *url = [NSURLURLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   
//2、建立请求对象
   
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];
   
    request.
HTTPMethod = @"post";
   
   
NSString *strBody = [NSStringstringWithFormat:@"submit =1&username = %@&password =%@",self.usernameTextField.text,self.passwordTextField.text];
   
    request.
HTTPBody = [strBody dataUsingEncoding:NSUTF8StringEncoding];
   
   
//request.HTTPBody = [[NSData alloc]initWithBytes:[strBody UTF8String] length:strBody.length];
   
//3、建立连接,发送请求
   
NSURLConnection *conn = [NSURLConnectionconnectionWithRequest:request delegate:self];
    [conn
start];
   
}

- (
void)viewDidLoad
{
    [
superviewDidLoad];
}

#pragma mark - NSURLConnectionDataDelegate方法
#pragma mark
收到数据时调用的方法,可能收到多个数据包,在这个方法中完成数据包的拼接
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [
self.fullDataappendData:data];


}
#pragma mark 数据接收完毕时的方法,对接收到的数据进行解析,进行相应的处理
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   
unsignedlong encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
   
NSString *str = [[NSStringalloc]initWithData:self.fullDataencoding:encode];
   
NSLog(@"接收到数据:%@",str);
   
//    UIImage *image = [UIImage imageWithData:self.fullData];
//    self.imageView.image = image;

}
-(
void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

   
NSLog(@"连接出错:%@",error);
}
在Ajax中,同步请求异步请求是两种不同的请求方式。 同步请求是指在发送请求后,浏览器会等待服务器返回响应后再继续执行后续的代码。也就是说,在同步请求中,浏览器会阻塞页面的加载和用户的交互,直到服务器返回响应为止。 异步请求是指在发送请求后,浏览器不会等待服务器返回响应,而是继续执行后续的代码。当服务器返回响应时,浏览器会触发相应的事件处理程序来处理响应。在异步请求中,页面的加载和用户的交互不会被阻塞,用户可以继续进行其他操作。 下面是一个示例代码,展示了同步请求异步请求的差别: ```javascript // 同步请求示例 var xhrSync = new XMLHttpRequest(); xhrSync.open('GET', 'https://example.com/api/data', false); // 第三个参数设置为false表示同步请求 xhrSync.send(); console.log(xhrSync.responseText); // 在请求完成后,直接获取响应内容 // 异步请求示例 var xhrAsync = new XMLHttpRequest(); xhrAsync.open('GET', 'https://example.com/api/data', true); // 第三个参数设置为true表示异步请求 xhrAsync.onload = function() { if (xhrAsync.status === 200) { console.log(xhrAsync.responseText); // 在事件处理程序中获取响应内容 } }; xhrAsync.send(); console.log('请求已发送'); // 在请求发送后,继续执行后续的代码 ``` 在上面的示例中,同步请求会阻塞代码的执行,直到服务器返回响应后才会继续执行后续的代码。而异步请求则不会阻塞代码的执行,可以在请求发送后继续执行后续的代码,待服务器返回响应时再触发事件处理程序来处理响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值