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. JavaScript跨域总结与解决办法(转)

    什么是跨域 1.document.domain+iframe的设置 2.动态创建script 3.利用iframe和location.hash 4.window.name实现的跨域数据传输 5.使用H ...

  2. 我的UI启蒙之路

    为什么叫UI启蒙之路呢? 我没有学过美术,也不懂设计,但是有的时候也许就是一种命中注定吧,让我知道了UI,并且一发不可收拾的爱上了它. 具体情况是这样的: 我毕业于电力学校,是一名不折不扣的工科生,专 ...

  3. 局域网2台机器访问mysql服务器

  4. linux 硬盘分区攻略

    以下的sdX代表硬盘分区(如sda1,sda2,sdb1...等等),如果已有的硬盘分区需要改变大小的话,请参考另一篇文章. /boot:开机用的磁盘空间了,至少78MB,一般给100MB就好了. / ...

  5. Spring boot 默认静态资源路径与手动配置访问路径的方法

    这篇文章主要介绍了Spring boot 默认静态资源路径与手动配置访问路径的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下   在application.propertis中配置 ##端口号 ...

  6. 2018.07.06 POJ1273 Drainage Ditches(最大流)

    Drainage Ditches Time Limit: 1000MS Memory Limit: 10000K Description Every time it rains on Farmer J ...

  7. EXT combobox 二级连动 清空store缓存数据

    项目中有这样的一个需求,做一个连动操作,如图: 所属行业中的combobox中下拉框中的值会根据前一个选择框中的值动态去变化,这个其实非常好做,但不是我现在讨论的主要问题,主要问题是,当第二次选择了& ...

  8. c++ => new/delete

    new的具体使用方式如下: 类型 *变量名 = new 类型; delete 变量 / delete[] 变量; 类型包括数组.结构体和类 数组申请动态内存后,要使用delete[]才能把内存清除干净 ...

  9. 61 origin授控于MATLAB

    官方教程:http://www.originlab.com/forum/topic.asp?TOPIC_ID=22339 学习自白东升老师originPRO8.0教程. 我用的是origin pro2 ...

  10. QGIS Server Quickstart

    http://live.osgeo.org/en/quickstart/qgis_mapserver_quickstart.html