1:NSData + NSURL

- (void)FF_LoadImageWithURLString:(NSString *)urlStr imageBlock:(ImageBlock)imageRequestCompleteBlock {
if (urlStr && urlStr.length > ) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
dispatch_async(dispatch_get_main_queue(), ^{
imageRequestCompleteBlock([UIImage imageWithData:data]);
});
});
}
}

*  通过NSMutableRequest 来指定请求的方式(HTTPMethod)请求体(HTTPBody)等

2: NSURLConnection (已经被废弃)

可以通过Block或者delegate的形式来获取请求完成的数据

- (void)FF_loadDataUseNSURLConnection:(NSString *)url block:(ImageBlock)completeBlock {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
/// 异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
/// 在主线程中
completeBlock([UIImage imageWithData:data]);
}];
NSLog(@"是异步执行");
}

deleaget形式

- (void)FF_LoadDataUseNSURLConnectionDelegate:(NSString *)url block:(ImageBlock)completeBlock {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
request.HTTPMethod = @"post";
request.HTTPBody = [@"" dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection connectionWithRequest:request delegate:self];
self.needBlcok = completeBlock;
} - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
long mm = response.expectedContentLength; self.mdata = [NSMutableData data]; NSLog(@"收到响应 %.2f", mm / 1024.0 / );
} - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.mdata appendData:data];
NSLog(@"收到数据");
} - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.needBlcok([UIImage imageWithData:self.mdata]);
NSLog(@"借宿请求");
}

3: NSURLSession

- (void)FF_LoadDataUseNSURLSession:(NSString *)url block:(ImageBlock)completeblock {
[NSURLSession sharedSession];
//NSURLSessionDataTask NSURLSessionUploadTask NSURLSessionDownloadTask NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
// 将JSON数据转化成Object
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@", dic);
// completeblock([UIImage imageWithData:data]);
});
}];
[task resume];
}

delegate形式

- (void)FF_LoadDataUseNSURLSessionDelgate:(NSString *)url block:(ImageBlock)completeBlock {
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:url]];
self.needBlcok = completeBlock;
[task resume];
} - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
self.mdata = [NSMutableData data];
/// 允许响应
completionHandler(NSURLSessionResponseAllow);
NSLog(@"开始响应");
} - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
[self.mdata appendData:data];
NSLog(@"收到数据");
} - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error {
if (error == nil) {
self.needBlcok([UIImage imageWithData:self.mdata]);
}
NSLog(@"完成请求");
} - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error {
NSLog(@"出现错误 %@", error.localizedDescription);
}

XML 解析 SAX, DOM

SAX解析(Simple API XML)逐行读入  可以立即停止解析,速度快,适用于读取 ,但是不能对XML进行修改

<?xml version="1.0" encoding="utf-8" ?>
<!--不引用任何的css文件,此时就能提取出所有的信息,标签除外,此种情况会将所有除标签之外的内容提出出来,排列在一行,当然我们可指定css文件改变这种布局-->
<?xml-stylesheet type="text/css" href="a.css" ?>
<contactlist>
<contect id="">
<name>张三</name>
<telephone></telephone>
</contect> <contect id="">
<name>李四</name>
<telephone></telephone>
</contect>
</contactlist> /// 生成解析器 系统自带
NSString *path = [[NSBundle mainBundle] pathForResource:@"aa" ofType:@"xml"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
if (parser) {
NSLog(@"....");
}else {
NSLog(@"不存在。。。");
}
/// 开始解析
BOOL bl = [parser parse];
if (bl) {
NSLog(@"---");
}else {
NSLog(@"+++");
} /// 代理
/// 系统自带的SAX(simple api xml)解析
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"开始解析");
self.marr = [@[] mutableCopy];
} /// 开始的元素
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict {
NSLog(@"%@", elementName);
if ([elementName isEqualToString:@"contect"]) {
self.peo = [[People alloc] init];
self.peo.aId = attributeDict[@"id"];
}else if ([elementName isEqualToString:@"name"]) {
self.isNeedEle = YES;
}else if ([elementName isEqualToString:@"telephone"]){
self.isNeedEle = YES;
}
} /// 找到元素
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (self.isNeedEle) {
if (self.mstr) {
[self.mstr appendString:string];
}else {
self.mstr = [NSMutableString stringWithFormat:@"%@", string];
}
}
NSLog(@"%@", string);
} /// 结束的元素
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName {
NSString *str = [self.mstr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[self.mstr setString:@""];
if ([elementName isEqualToString:@"name"]) {
_peo.name = str;
}else if ([elementName isEqualToString:@"telephone"]){
_peo.telephone = str;
}else if ([elementName isEqualToString:@"contect"]) {
[self.marr addObject:self.peo];
}
self.isNeedEle = NO;
NSLog(@"%@", elementName);
} ///
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"结束解析");
NSLog(@"%@", self.marr);
}

DOM解析 (Document Object Model) 第三方解析 GDataXMLNode  全部读入。占用内存,时间长,但是可以把XML文件在内存中构建属性结构,可以遍历和修改节点。

1:导入GDataXMLNode之后会报错,根据提示修改即可

 // libxml includes require that the target Header Search Paths contain
// Targets -> Build Settings -> 搜索Header Search Paths 添加
// /usr/include/libxml2
// Targets -> Build Settings -> 搜索Other Linker Flags 添加
// and Other Linker Flags contain
//
// -lxml2
    // 下载地址 https://github.com/graetzer/GDataXML-HTML
//GDataXMLNode解析方式 使用的是 DOM(Document Object Model)
NSString *path = [[NSBundle mainBundle] pathForResource:@"aa" ofType:@"xml"];
NSData *data = [NSData dataWithContentsOfFile:path];
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data error:nil];
NSArray<GDataXMLElement *> *arr = [doc.rootElement elementsForName:@"contect"];
self.marr = [@[] mutableCopy];
for (GDataXMLElement *ele in arr) {
People *pe = [[People alloc] init];
/// 获取的下面的节点
for (GDataXMLNode *node in ele.children) {
if ([node.name isEqualToString:@"name"]) {
pe.name = node.stringValue;
}
if ([node.name isEqualToString:@"telephone"]) {
pe.telephone = node.stringValue;
}
}
/// 获取的是属性节点数组
for (GDataXMLNode *node in ele.attributes) {
if ([node.name isEqualToString:@"id"]) {
pe.aId = node.stringValue;
}
}
[self.marr addObject:pe];
}

基础Network Request的更多相关文章

  1. Network Request Failed

    在react native项目中,有时候调用接口会出现这样的错误提示:“Network Request Failed”. 一.模拟器上报“Network Request Failed”解决办法,也是官 ...

  2. 解决React Native使用Fetch API请求网络报Network request failed

    问题来源: 1 . 在测试fetch数据请求时,Xcode9.0以上的无法请求https, 需要在Xcode中加载项目后修改Info.plist的相关配置,具体如下参考 问题及解决方法一模一样,不再重 ...

  3. reactNative-解决react native使用fetch函数 Network request failed 问题

    解决react native使用fetch函数Network request failed问题 最近公司新开发一个app, 用react native架构好后,用xcode模拟器打开app,对接登陆接 ...

  4. react native TypeError network request failed

        如果使用fetch获取数据,用的是POST方法,注意headers要添加请求头.当请求为GET时不能用body,当为POST时必须包含body,设置头部之后就一切正常了.   fetch(&q ...

  5. Django基础之request对象

    当一个页面被请求时,django就会创建一个包含本次请求原信息的HttpRequest对象. django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用request参数承接这个对象 ...

  6. 爬虫基础(一)-----request模块的使用

    ---------------------------------------------------摆脱穷人思维 <一>  :   建立时间价值的概念,减少做那些"时间花的多收 ...

  7. Android 使用 NYTimes Stores 缓存 network request

    NYTimes Stores 是一个缓存库,在 2017年的 AndroidMakers 大会上被介绍过. https://github.com/NYTimes/Store 实现一个 Disk Cac ...

  8. npm WARN network …… request to https://cnpmjs.…… failed, reason: socket hang up

    出现类似问题的原因是由于之前配置了镜像导致的 解决方案:删掉镜像,使用npm本身进行安装 删除镜像的命令: 方法1: npm config delete registry 方法2: npm confi ...

  9. django基础2: 路由配置系统,URLconf的正则字符串参数,命名空间模式,View(视图),Request对象,Response对象,JsonResponse对象,Template模板系统

    Django基础二 request request这个参数1. 封装了所有跟请求相关的数据,是一个对象 2. 目前我们学过1. request.method GET,POST ...2. reques ...

随机推荐

  1. 我对于UI设计这个领域的理解

    User Interface(UI),包括三部分用户.界面以及用户与界面之间的交互关系.UI设计则是指对软件的人机交互.操作逻辑.界面美观的整体设计. 如何看待UI设计这个领域? 任何一个行业的出现都 ...

  2. 设置zookeeper为systemctl守护进程

    ==目的== 想把zookeeper.hadoop.hbase.storm等大数据组件 设置为开机启动,并且进程挂掉之后,可以自动重启,以减少运维压力. ==service文件== 路径:/usr/l ...

  3. $.post 提示错误: Uncaught SyntaxError: Unexpected token :

    $.post("addRecommond",{"productId":productId,"categoryCode":categoryCo ...

  4. android通过 Intent 传递类对象

    Android中Intent传递类对象提供了两种方式一种是 通过实现Serializable接口传递对象,一种是通过实现Parcelable接口传递对象. 要求被传递的对象必须实现上述2种接口中的一种 ...

  5. myeclipse 中 svn 更新 提交 同步资源库 详细解释下他们的功能

    原理是这样的 svn服务器一般放在公共的服务器上,大家连这个服务器,在MyEclipse上使用svn控件 可以下载svn上的项目至本地,所以很多公司将开发要用到的软件都放在svn上,有同事来只要连上s ...

  6. 提高搜狗SR值和关键词排名

    凭借“输入法-浏览器-搜索”三级火箭战略,搜狗搜狗使用率已超过10%,并成功挤掉谷歌成为国内第二大搜索引擎服务提供商.随着搜狗的快速发展,越来越多的站长将目光投向针对搜狗搜索的关键词优化. 大家都知道 ...

  7. 2018.09.07 loj#10166 数字游戏(数位dp)

    传送门 数位dp板子题. f[i][mod]" role="presentation" style="position: relative;"> ...

  8. swagger core 和 swagger ui 如何关联【窥探】

    几个片段: package io.swagger.jaxrs.listing; import io.swagger.annotations.ApiOperation; import org.apach ...

  9. 01-html和head介绍

    一.web标准 web准备介绍: w3c:万维网联盟组织,用来制定web标准的机构(组织) web标准:制作网页遵循的规范 web准备规范的分类:结构标准.表现标准.行为标准. 结构:html.表示: ...

  10. spring boot docker 初尝试

    Docker服务中进程间通信通过/var/run/docker.sock实现,默认服务不提供监听端口,因此使用docker remote api 需要手动绑定端口. 在centos7.2下,可以进行这 ...