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. DLL另類劫持注入法

    // Win32Project2.cpp : 定义 DLL 应用程序的导出函数. // //////////////////////////////////////////////////////// ...

  2. 使用jsonp跨域发送请求

    如果获取的数据文件存放在远程服务器上(域名不同,也就是跨域获取数据),则需要使用jsonp类型. 使用这种类型的话,会创建一个查询字符串参数 callback=? ,这个参数会加在请求的URL后面. ...

  3. c++ 对象复制引用时何时调用构造函数、析构函数

    class TEST{ private : public : TEST() {std::cout << "constructor" << std::endl ...

  4. Laravel Eloquent Model->isDirty() Function

    1 引言 introduction 有时,我们需要在 Model 某些属性发生变化时,作出相应的处理. 这时,我们可以使用 Model->isDirty() 方法进行判断. 2 场景 比如,姓名 ...

  5. 创建cookie

    cookie的创建using System;using System.Collections.Generic;using System.Linq;using System.Web;using Syst ...

  6. android的 Base64

    byte[] key=Base64.decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4".getBytes(), Base64.DEFAULT);   ...

  7. 2018.09.17 atcoder Tak and Hotels(贪心+分块)

    传送门 一道有意思的题. 一开始想错了,以为一直lowerlowerlower_boundboundbound就可以解决询问,结果交上去TLE了之后才发现时间复杂度是错的. 但是贪心思想一定是对的,每 ...

  8. JPA数据懒加载LAZY和实时加载EAGER(转)

    原文:https://www.cnblogs.com/MrSi/p/8081811.html 懒加载LAZY和实时加载EAGER的概念,在各种开发语言中都有广泛应用.其目的是实现关联数据的选择性加载, ...

  9. 【转】MapReduce:详解Shuffle过程

    ——转自:{http://langyu.iteye.com/blog/992916} Shuffle过程是MapReduce的核心,也被称为奇迹发生的地方.要想理解MapReduce, Shuffle ...

  10. HDU 5618 Jam's problem again (cdq分治+BIT 或 树状数组套Treap)

    题意:给n个点,求每一个点的满足 x y z 都小于等于它的其他点的个数. 析:三维的,第一维直接排序就好按下标来,第二维按值来,第三维用数状数组维即可. 代码如下: cdq 分治: #pragma ...