网络请求之get与post异步请求

直接上源码了,等了解比较透彻的时候在做详细讲解

.h文件源码

//
//  DSRequestManager.h
//  DeseDAZ
//
//  Created by 安浩 on 15/6/19.
//  Copyright (c) 2015年 DAZ. All rights reserved.
//

/**
 *  网络请求
 */
#import <Foundation/Foundation.h>

//声明一个 blcok 属性 用来传值
//finishBlcok 把请求完毕 解析好的数据传出来  id 可以代表任意类型
typedef void (^FinishBlock)(id dataResponse);

@interface DSRequestManager : NSObject<NSURLConnectionDelegate>

@property (nonatomic,strong) NSMutableData *resultData;

@property (nonatomic,strong) FinishBlock finishBlock;


/**
 *  post 类方法
 *
 *  @param urlStr    接口参数  内部设计了接口基本链接的宏 只传后面跟的接口参数
 *  @param paramters 需要传的参数
 *  @param block     返回值
 */
+ (void)postRequestWithURL:(NSString *)urlStr
                 paramters:(NSDictionary *)paramters
              finshedBlock:(FinishBlock)block;


/**
 *  get 类方法
 *
 *  @param urlStr 接口参数  
 *  @param block  返回值
 */
+ (void)getRequestWithURL:(NSString *)urlStr
                paramters:(NSDictionary *)paramters
             finshedBlock:(FinishBlock)block;


@end

.m文件源码

//
//  DSRequestManager.m
//  DeseDAZ
//
//  Created by 安浩 on 15/6/19.
//  Copyright (c) 2015年 DAZ. All rights reserved.
//

#import "DSRequestManager.h"
#import "APIHeader.h"
@implementation DSRequestManager


#pragma mark ----------post----------
/**
 *  post 类方法
 *
 *  @param urlStr    接口参数  内部设计了接口基本链接的宏 只传后面跟的接口参数
 *  @param paramters 需要传的参数
 *  @param block     返回值
 */
+ (void)postRequestWithURL:(NSString *)urlStr
                 paramters:(NSDictionary *)paramters
              finshedBlock:(FinishBlock)block{
    
    
    DSRequestManager *requestManager =[DSRequestManager new];
    
    requestManager.finishBlock = block;
    //拼接接口
    NSString *str =[NSString stringWithFormat:@"%@%@",PKAPI,urlStr];
    //转化 url
    NSURL *url = [NSURL URLWithString:str];
    
    //使用 NSMutableURLRequest 创建对象
    //NSURLRequest 是一个不可变的请求,默认执行的就是GET请求。也就是说,通过NSURLRequest无法指定 请求方式为 POST,因为TA是不可变的。
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
    [request setHTTPMethod:@"POST"];
    
    //准备发送的字符串
    NSString *postStr = @"";
    //取出post参数中所有key
    NSArray *keyArray = [paramters allKeys];
    //遍历 拼接参数的字符串
    for (NSString *keyString in keyArray) {
        
        postStr = [NSString stringWithFormat:@"%@&%@=%@",postStr,keyString,[paramters objectForKey:keyString]];
        
    }
    
    [request setHTTPBody:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    //发出请求
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:requestManager];

    NSLog(connection ? @"网络连接创建成功" : @"网络连接连接创建失败");
    
}

#pragma mark ---------get----------
/**
 *  get 类方法
 *
 *  @param urlStr 接口参数
 *  @param block  返回值
 */
+ (void)getRequestWithURL:(NSString *)urlStr
                paramters:(NSDictionary *)paramters
             finshedBlock:(FinishBlock)block{
    
    DSRequestManager *requestManager =[DSRequestManager new];
    
    requestManager.finishBlock = block;
    
    //准备发送的字符串
    NSMutableString *getStr = [urlStr mutableCopy];
    [getStr appendString:@""];
    //取出post参数中所有key
    NSArray *keyArray = [paramters allKeys];
    //遍历 拼接参数的字符串
    for (NSString *keyString in keyArray) {
        
        getStr = [NSMutableString stringWithFormat:@"%@&%@=%@",getStr,keyString,[paramters objectForKey:keyString]];
    }

    NSURL *url = [NSURL URLWithString:[getStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:requestManager];
   NSLog(connection ? @"网络连接创建成功" : @"网络连接连接创建失败");

}



/**
 *  接收到服务器回应的时回调
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if (!self.resultData) {
        self.resultData = [[NSMutableData alloc]init];
    } else {
        [self.resultData setLength:0];
    }
    
    if ([response respondsToSelector:@selector(allHeaderFields)]) {
        // 取得所有的请求的头
        NSDictionary *dic = [httpResponse allHeaderFields];
        NSLog(@"network---Header:%@",[dic description]);
    }
}
/**
 *  接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.resultData appendData:data];
}
/**
 *  数据传完之后调用此方法
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    NSError *error;


    id dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        NSLog(@"解析错误");
        self.finishBlock(nil);
    }
    
    if (self.finishBlock) {
        self.finishBlock(dic);
    }
}
/**
 *  网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"network error : %@", [error localizedDescription]);
    
    if (self.finishBlock) {
        self.finishBlock(nil);
    }
}


@end

HTTP 方法:GET 对比 POST

暂时留链接 http://www.w3school.com.cn/tags/html_ref_httpmethods.asp
http://www.w3school.com.cn/jquery/jquery_ajax_get_post.asp

推荐博客链接:http://www.brighttj.com/ios/ios-http-request-post-get.html

On the road。。。
原文地址:https://www.cnblogs.com/ianhao/p/4589884.html