MKNetworkKit GET和POST的使用

简单说一下GET和POST的不同之处:

GET请求,它是将参数直接写在访问路径中,参数用&连接。操作简单,但是安全性不高。

POST请求,它是将参数放在body中。由于路径和参数是分开的,所以安全性较高。


举例说明:

GET请求的路径为:

https://api.weibo.com/user_timeline.json?access_token=xxx&uid=xxx

其中基本的URL是https://api.weibo.com/user_timeline.json

参数2个:access_token和uid

POST请求的路径为:

https://api.weibo.com/user_timeline.json

参数以字典的方式存放在HTTPbody中。


以下分别展示了MKNetworkKit下GET和POST请求的代码:

GET请求的代码如下:

NSString *cityName = @"北京";
    // 路径中中文需要转成专门用于URL的编码格式
    cityName = [cityName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *host = @"192.168.0.30:82";
    NSString *path = [NSString stringWithFormat:@"getWeater?cityName=%@",cityName];
    
    //header中可以放附加信息,如时间、设备等等
    NSMutableDictionary *header = [[NSMutableDictionary alloc] init];
    [header setValue:@"text/xml; charset=utf-8" forKey:@"Content-Type"];
    
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:host customHeaderFields:header];
    MKNetworkOperation *operation = [engine operationWithPath:path];
    
    [operation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        NSLog(@"请求完成");
    
        // 获得返回的数据(字符串形式)
        NSString *result = [completedOperation responseString];//responseData 二进制形式
        NSLog(@"返回数据:%@", result);
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        NSLog(@"请求出错");
    
    }];
    
    // 发起网络请求
    [engine enqueueOperation:operation];


POST请求的代码如下;

NSString *cityName = @"北京";
    cityName = [cityName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //目标URL:http://192.168.0.30:82/getWeather
    
    NSString *host = @"192.168.0.30:82";
    // 域名(host)后面跟着的路径,
    NSString *path = [NSString stringWithFormat:@"getWeater"];
    
    //参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:cityName forKey:@"cityName"];
    
    // path 值可以放到 engine 的初始化中,也可以放到 operation 的初始化中,效果一样
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:host apiPath:path customHeaderFields:nil];
    MKNetworkOperation *operation = [engine operationWithPath:nil params:params httpMethod:@"POST"];
    
    // 添加网络请求完成处理逻辑
    [operation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        NSLog(@"请求完成");
        
        // 获得返回的数据(字符串形式)
        NSString *result = [completedOperation responseString];//responseData 二进制形式
        NSLog(@"返回数据:%@", result);
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        NSLog(@"请求出错");
        
    }];
    
    // 发送网络请求
    [engine enqueueOperation:operation];












你可能感兴趣的:(ios,xcode)