博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网络请求之get与post异步请求
阅读量:4575 次
发布时间:2019-06-08

本文共 5173 字,大约阅读时间需要 17 分钟。

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

.h文件源码

////  DSRequestManager.h//  DeseDAZ////  Created by 安浩 on 15/6/19.//  Copyright (c) 2015年 DAZ. All rights reserved.///** *  网络请求 */#import 
//声明一个 blcok 属性 用来传值//finishBlcok 把请求完毕 解析好的数据传出来 id 可以代表任意类型typedef void (^FinishBlock)(id dataResponse);@interface DSRequestManager : NSObject
@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

转载于:https://www.cnblogs.com/ianhao/p/4589884.html

你可能感兴趣的文章
为什么使用Nosql:Nosql和SQL的区别
查看>>
<转>DNS服务系列之二:DNS区域传送漏洞的安全案例
查看>>
LINUX中常用操作命令
查看>>
【android】动画效果研究(View)【1】
查看>>
(三)常用的数学函数
查看>>
生产信息集成分析平台(MIIAS V1.0) 概述
查看>>
学习进度——第十五周
查看>>
简谈-网络爬虫的几种常见类型
查看>>
File对象目录列表器
查看>>
(K)ubuntu上将分区格式化成NTFS格式
查看>>
mysql5.7二进制包安装方式
查看>>
装饰者模式——Java设计模式
查看>>
39.递推练习: 菲波那契数列(2)
查看>>
排序精讲
查看>>
【bzoj3172】 Tjoi2013—单词
查看>>
【uoj2】 NOI2014—起床困难综合症
查看>>
js return的用法
查看>>
子节点填充父元素除去一固定高度后的剩余高度
查看>>
[原]IOS 后台发送邮件
查看>>
(转)JAVA Calendar详解
查看>>