iOS-ASI

李经国
2023-12-01
//
//  ViewController.m
//  网络_ASI_
//
//  Created by 邱学伟 on 15/10/7.
//  Copyright (c) 2015年 xuewei. All rights reserved.
//

#import "ViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"

/**
 监听ASI的请求
 1.成为代理,遵守ASIHTTPRequestDelegate协议,实现协议中的代理方法
 request.delegate = self;
 - (void)requestStarted:(ASIHTTPRequest *)request;
 - (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;
 - (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;
 - (void)requestFinished:(ASIHTTPRequest *)request;
 - (void)requestFailed:(ASIHTTPRequest *)request;
 
 2.成为代理,不遵守ASIHTTPRequestDelegate协议,自定义代理方法
 request.delegate = self;
 [request setDidStartSelector:@selector(start:)];
 [request setDidFinishSelector:@selector(finish:)];
 
 3.设置block
 [request setStartedBlock:^{
 NSLog(@"setStartedBlock");
 }];
 [request setHeadersReceivedBlock:^(NSDictionary *responseHeaders) {
 NSLog(@"setHeadersReceivedBlock--%@", responseHeaders);
 }];
 [request setDataReceivedBlock:^(NSData *data) {
 NSLog(@"setDataReceivedBlock--%@", data);
 }];
 [request setCompletionBlock:^{
 NSLog(@"setCompletionBlock");
 }];
 [request setFailedBlock:^{
 NSLog(@"setFailedBlock");
 }];
 */


@interface ViewController ()  <ASIHTTPRequestDelegate,ASIProgressDelegate>
@property (nonatomic, strong) ASIHTTPRequest *request;
@property (nonatomic, weak) IBOutlet UIProgressView *progressView;
@property (nonatomic, assign) BOOL downloading;
@end

@implementation ViewController

- (void)viewDidLoad {
    
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self upload];
    
    
}

//---------------------------------------------------------------------------

//ASI文件上传
-(void)upload{
    
    //1、URL
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/upload"];
    //2、创建请求对象
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
   
    //3、设置请求参数
    [request setPostValue:@"123" forKey:@"username"];
    [request setPostValue:@"123" forKey:@"pwd"];
  
    //4、设置文件参数
    //方式一:如果知道文件路径最好使用这个方式(简单),ASI内部会自动识别文件的MIMType
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"04-Modal" ofType:@"mp4"];
    [request setFile:filePath forKey:@"file"];
    
    //方式二:(一般不用)
    [request setFile:filePath withFileName:@"005.png" andContentType:@"application/vnd.openxmlformats-officedocument.presentationml.presentation" forKey:@"file"];
    
    //方式三:如果文件是动态产生的,就用这个方法(比如刚拍完照获得的图片数据)
//    request setData:<#(id)#> withFileName:<#(NSString *)#> andContentType:<#(NSString *)#> forKey:<#(NSString *)#>
    
    //设置监听上传进度的代理
    request.uploadProgressDelegate = self.progressView;
    
    
    //5、开始请求
    [request startAsynchronous];
    
    //监听完毕
    __weak typeof(request) weakrequest = request;
    [request setCompletionBlock:^{
        
        NSLog(@"上传完毕0-----%@",[weakrequest responseString]);
    }];
    

}

//---------------------------------------------------------------------------

//ASI文件下载
-(void)download{
    
    if (self.downloading) {
        [self.request clearDelegatesAndCancel];
        self.downloading = NO;
    }else{
        
        //URL
        NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/js.mp4"];
        
        //创建请求
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        request.timeOutSeconds = 10;
        
        //设置文件下载路径
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [caches stringByAppendingPathComponent:@"jjs.mp4"];
        request.downloadDestinationPath = filePath;
        
        
        //以上就可以下载文件,,如果想监听下载进度则
        
        //设置进度监听的代理(要想成为进度监听代理,最好遵守ASIProgressDelegate协议)
        //    request.downloadProgressDelegate = self;
        //直接设置为进度条的代理更简单,不用实现setProgress方法,会自动调用progressView的set方法
        request.downloadProgressDelegate = self.progressView;
        
        /**
         
         断点续传:
         request.allowResumeForFileDownloads = YES;
         request.temporaryFileDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.temp"];
         
         */
        
        
        //开始请求
        [request startAsynchronous];
        
        self.request = request;
        self.downloading = YES;
    }
    
    
}


//-(void)setProgress:(float)newProgress{
//    NSLog(@"下载进度——————-%f",newProgress);
//}

//---------------------------------------------------------------------------

//ASI发送POST请求——需要导入ASIFormDataRequest.h 类
-(void)asynPost{
    
    //url
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"];
    
    //创建一个请求_ASIFormDataRequest 这默认就是发送POST请求
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    //设置请求参数(建议使用setPostValue)
    [request setPostValue:@"123" forKey:@"username"];
    [request setPostValue:@"123" forKey:@"pwd"];
    
    //开始请求
    [request startAsynchronous];
    
    //设置监听方法
    __weak typeof(request) weakRequest = request;
    [request setCompletionBlock:^{
        NSLog(@"请求完毕-----%@",[weakRequest responseString]);
    }];
    
}

//---------------------------------------------------------------------------


//直接设置监听方法
-(void)setMoniterMethod{
    //url
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];
    
    //创建请求
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.timeOutSeconds = 10;
    
    //开始请求
    [request startAsynchronous];
    
    //设置监听方法
    request.delegate = self;
    [request setDidStartSelector:@selector(start:)];
    [request setDidFinishSelector:@selector(finish:)];
    
}

-(void)start:(ASIHTTPRequest *)request{
    NSLog(@"start -- %@",request);
}


-(void)finish:(ASIHTTPRequest *)request{
    NSLog(@"finish -- %d,  %@,  %@",[request responseStatusCode],[request responseStatusMessage],[request responseData]);
}

//---------------------------------------------------------------------------

//异步block监听
-(void)asyncBlock{
    
    //URL
    NSURL *URL = [NSURL URLWithString:@"HTTP://localhost:8080/MJServer/video"];
    
    //创建一个请求
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:URL];
    //设置请求响应时间
    request .timeOutSeconds = 10;
    
    //开始请求
    [request startAsynchronous];
    
    /**
     如果同时设置了代理方法和block,请求过程中,两个都会调用
     一般的调用顺序:代理方法>block
     request.delegate = self ;
     */
    
    //设置block监听
    [request setStartedBlock:^{
        NSLog(@"setStartedBlock");
    }];
    
    [request setHeadersReceivedBlock:^(NSDictionary *responseHeaders) {
        NSLog(@"setHeadersReceivedBlock-----%@",responseHeaders);
    }];
    
    [request setDataReceivedBlock:^(NSData *data) {
        NSLog(@"setDataReceivedBlock------\n%@",data);
    }];
    
    [request setCompletionBlock:^{
        NSLog(@"setCompletionBlock");
    }];
    
    [request setFailedBlock:^{
        NSLog(@"setFailedBlock");
    }];
    
}


//---------------------------------------------------------------------------


//异步的GET请求
-(void)asynGet{
    
    //URL
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];
    
    //创建一个请求
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置请求响应时间
    request.timeOutSeconds = 10;
    //设置代理
    request.delegate = self;
    
    //开始请求
    [request startAsynchronous];
    
    self.request = request;
    
    
}

#pragma  mark - 实现ASIHTTPRequest的代理方法



//1、开始发送请求
-(void)requestStarted:(ASIHTTPRequest *)request{
    NSLog(@"requestStarted");
}

//2、接收到服务器的响应头信息
-(void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders{
    NSLog(@"didReceiveResponseHeaders");
    
}

//3、接收到服务器的实体数据(具体数据——调用多次)---(除非监听下载进度否则不要使用)

//!!!只要实现了这个方法,就意味着用户自己处理数据,responseData和responseString没有值
//-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{
//    NSLog(@"didReceiveData");
//}


//4、服务器的响应数据接收完毕
-(void)requestFinished:(ASIHTTPRequest *)request{
    NSLog(@"requestFinished");
    
    
}

//5、请求失败调用
-(void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"requestFailed");
}

//同步的GET请求
-(void)synGet{
    //1、url
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];
    
    //2、创建一个请求对象
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置超时时间
    request.timeOutSeconds = 10;
    
    //3、开始请求
    [request startSynchronous];
    
    //4、请求完毕
    NSError *error = [request error];
    if (error) {
        NSLog(@"请求失败---%@",error);
    }else{
        NSData *data = [request responseData];
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"请求成功---%@",dict);
    }

}
@end


 类似资料: