• MKNetworkKit的使用


     

    链接:http://blog.csdn.net/lookyou111/article/details/26450663

     

    使用方法:

      在需要使用的地方导入:#import"MKNetworkKit.h"

     http方式:

     

        GET请求:     

    [cpp] view plaincopy
     
     
    1. MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"192.168.2.176:3000" customHeaderFields:nil];  
    2. MKNetworkOperation *op = [engine operationWithPath:@"/index" params:nil httpMethod:@"GET" ssl:NO];  
    3. [op addCompletionHandler:^(MKNetworkOperation *operation) {  
    4.     NSLog(@"[operation responseData]-->>%@", [operation responseString]);  
    5. }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {  
    6.     NSLog(@"MKNetwork request error : %@", [err localizedDescription]);  
    7. }];  
    8. [engine enqueueOperation:op];  

        POST请求:

    [cpp] view plaincopy
     
     
    1. MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"192.168.2.176:3000" customHeaderFields:nil];  
    2. NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];  
    3. [dic setValue:@"admin" forKey:@"username"];  
    4. [dic setValue:@"123" forKey:@"password"];  
    5.   
    6. MKNetworkOperation *op = [engine operationWithPath:@"/login" params:dic httpMethod:@"POST"];  
    7. [op addCompletionHandler:^(MKNetworkOperation *operation) {  
    8.     NSLog(@"[operation responseData]-->>%@", [operation responseString]);  
    9. }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {  
    10.     NSLog(@"MKNetwork request error : %@", [err localizedDescription]);  
    11. }];  
    12. [engine enqueueOperation:op];  

        https方式:

    [cpp] view plaincopy
     
     
    1. #define serverHost               @"192.168.1.84:5558"  
    2.   
    3. - (NSDictionary *)getDataFromURL:(NSString *)Path params:(NSDictionary *)data  
    4. {  
    5.     NSLog(@"MKNetwork request URL:  %@%@     Data: %@",serverHost,Path,data);  
    6.       
    7.     __block NSDictionary *responseJSON;  
    8.     __block NSError *error = nil;  
    9.     MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:serverHost customHeaderFields:nil];  
    10.     MKNetworkOperation *op = [engine operationWithPath:Path  params:data httpMethod:@"POST" ssl:YES];  
    11. //    在请求中添加证书  
    12.     op.clientCertificate = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"client.p12"];  
    13.     op.clientCertificatePassword = @"test";  
    14. //   当服务器端证书不合法时是否继续访问  
    15.     op.shouldContinueWithInvalidCertificate=YES;  
    16.     [op addCompletionHandler:^(MKNetworkOperation *operation) {  
    17.         NSLog(@"[operation responseData]-->>%@", [operation responseString]);  
    18.         responseJSON=[NSJSONSerialization JSONObjectWithData:[operation responseData] options:kNilOptions error:&error];  
    19.         if(error) {  
    20.             NSLog(@"JSONSerialization failed! - error: %@", error);  
    21.         };  
    22.         error=nil;  
    23.     } errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {  
    24.         error=err;  
    25.     }];  
    26.     [engine enqueueOperation:op];  
    27.     while(!error&&!responseJSON){}  
    28.     if (error) {  
    29.         NSLog(@"MKNetwork request error : %@", error);  
    30.         return nil;  
    31.     }  
    32.     if(responseJSON){  
    33.         NSLog(@"JSONSerialization successed! - responseJSON: %@", responseJSON);  
    34.     }  
    35.     return responseJSON;  
    36. }  
    37.   
    38.   
    39.     NSDictionary *params=[NSDictionary dictionaryWithObjectsAndKeys:@"admin",@"userName", @"123",@"password", nil];  
    40.     NSDictionary *responseDict = [self getDataFromURL:@"/login" params:params];  
     

    下载文件:

    [cpp] view plaincopy
     
     
    1. +(MKNetworkOperation*) downloadFatAssFileFrom:(NSString*) remoteURL toFile:(NSString*) filePath {  
    2.     MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"127.0.0.1:5558" customHeaderFields:nil];  
    3.     MKNetworkOperation *op = [engine operationWithURLString:remoteURL  
    4.                                                    params:nil  
    5.                                                httpMethod:@"GET"];  
    6.       
    7.     [op addDownloadStream:[NSOutputStream outputStreamToFileAtPath:filePath  
    8.                                                             append:YES]];  
    9.     [engine enqueueOperation:op];  
    10.     return op;  
    11. }  
    12. +(void)testDownload{  
    13.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
    14.     NSString *cachesDirectory = [paths objectAtIndex:0];  
    15.     NSString *downloadPath = [cachesDirectory stringByAppendingPathComponent:@"DownloadedFile.pdf"];  
    16.       
    17.     MKNetworkOperation *downloadOperation=[HttpManager downloadFatAssFileFrom:@"http://127.0.0.1:5558/QQ"  
    18.                                                                       toFile:downloadPath];  
    19.       
    20.     [downloadOperation onDownloadProgressChanged:^(double progress) {  
    21.         //下载进度  
    22.         NSLog(@"download progress: %.2f", progress*100.0);  
    23.     }];  
    24.     //事件处理  
    25.     [downloadOperation addCompletionHandler:^(MKNetworkOperation* completedRequest) {  
    26.         NSLog(@"download file finished!");  
    27.     }  errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {  
    28.         NSLog(@"download file error: %@", err);  
    29.     }];  
    30. }  

    上传文件:

    [cpp] view plaincopy
     
     
    1. +(MKNetworkOperation*) uploadImageFromFile:(NSString*) filePath mimeType:(NSString *)fileType{  
    2.     MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"127.0.0.1:5558" customHeaderFields:nil];  
    3.     MKNetworkOperation *op = [engine operationWithPath:@"upload"  
    4.                                               params:[NSDictionary dictionaryWithObjectsAndKeys:  
    5.                                                       @"admin", @"username",  
    6.                                                       @"123", @"password",nil]  
    7.                                           httpMethod:@"POST"];  
    8.       
    9.     [op addFile:filePath forKey:@"media" mimeType:fileType];  
    10.       
    11.     // setFreezable uploads your images after connection is restored!  
    12.     [op setFreezable:YES];  
    13.       
    14.     [op addCompletionHandler:^(MKNetworkOperation* completedOperation) {  
    15.           
    16.         NSString *responseString = [completedOperation responseString];  
    17.         NSLog(@"server response: %@",responseString);  
    18.     } errorHandler:^(MKNetworkOperation *errorOp, NSError* err){  
    19.           
    20.         NSLog(@"Upload file error: %@", err);  
    21.     }];  
    22.       
    23.     [engine enqueueOperation:op];  
    24.       
    25.     return op;  
    26. }  
    27.   
    28. +(void)testUpload{  
    29.     NSString *uploadPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SampleImage.jpg"];  
    30.     //    NSData *myData = [NSData dataWithContentsOfFile:uploadPath];  
    31.     //    NSLog(@">>>>>>>>%@",myData);  
    32.     MKNetworkOperation *uploadOperation = [HttpManager uploadImageFromFile:uploadPath mimeType:@"jpg"];  
    33.     [uploadOperation onUploadProgressChanged:^(double progress) {  
    34.         //        上传进度  
    35.         DLog(@"Upload file progress: %.2f", progress*100.0);  
    36.     }];  
    37. }  

    上传文件时服务器端程序(Node.Js):

    [javascript] view plaincopy
     
     
    1. var express = require('express')  
    2.     ,fs=require('fs');  
    3.   
    4. var app = module.exports = express.createServer();  
    5. // Configuration  
    6. app.configure(function(){  
    7.     app.use(express.bodyParser());  
    8.     app.use(express.methodOverride());  
    9.     app.use(app.router);  
    10. });  
    11. // Routes  
    12. app.post('/upload', function(req, res) {  
    13.     console.log(req);  
    14.     var tmp_path = req.files.media.path; // 获得文件的临时路径  
    15.     var target_path = './'+req.files.media.name;// 指定文件上传后的目录  
    16.     fs.rename(tmp_path, target_path, function(err) { // 移动文件  
    17.         if (err) throw err;  
    18.         fs.unlink(tmp_path, function() {// 删除临时文件夹文件,  
    19.             if (err) throw err;  
    20.             res.send({server:'success'});  
    21.             res.end();  
    22.         });  
    23.     });  
    24. });  
    25. app.listen(5558);  
    26. console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.e
  • 相关阅读:
    subprocess(子进程模块)
    logging日志模块,hashlib hash算法相关的库,
    json pickle xml shelve configparser
    os与操作系统进行交互,sys解释器相关,random随机数,shutil解压和压缩
    目录规范+时间模块
    vue的组件
    drf 分页
    包和模块
    docker镜像&nginx配置
    匿名函数 递归 二分法 面向过程编程
  • 原文地址:https://www.cnblogs.com/PengFei-N/p/4766002.html
Copyright © 2020-2023  润新知