基础Network Request
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的更多相关文章
- Network Request Failed
在react native项目中,有时候调用接口会出现这样的错误提示:“Network Request Failed”. 一.模拟器上报“Network Request Failed”解决办法,也是官 ...
- 解决React Native使用Fetch API请求网络报Network request failed
问题来源: 1 . 在测试fetch数据请求时,Xcode9.0以上的无法请求https, 需要在Xcode中加载项目后修改Info.plist的相关配置,具体如下参考 问题及解决方法一模一样,不再重 ...
- reactNative-解决react native使用fetch函数 Network request failed 问题
解决react native使用fetch函数Network request failed问题 最近公司新开发一个app, 用react native架构好后,用xcode模拟器打开app,对接登陆接 ...
- react native TypeError network request failed
如果使用fetch获取数据,用的是POST方法,注意headers要添加请求头.当请求为GET时不能用body,当为POST时必须包含body,设置头部之后就一切正常了. fetch(&q ...
- Django基础之request对象
当一个页面被请求时,django就会创建一个包含本次请求原信息的HttpRequest对象. django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用request参数承接这个对象 ...
- 爬虫基础(一)-----request模块的使用
---------------------------------------------------摆脱穷人思维 <一> : 建立时间价值的概念,减少做那些"时间花的多收 ...
- Android 使用 NYTimes Stores 缓存 network request
NYTimes Stores 是一个缓存库,在 2017年的 AndroidMakers 大会上被介绍过. https://github.com/NYTimes/Store 实现一个 Disk Cac ...
- npm WARN network …… request to https://cnpmjs.…… failed, reason: socket hang up
出现类似问题的原因是由于之前配置了镜像导致的 解决方案:删掉镜像,使用npm本身进行安装 删除镜像的命令: 方法1: npm config delete registry 方法2: npm confi ...
- django基础2: 路由配置系统,URLconf的正则字符串参数,命名空间模式,View(视图),Request对象,Response对象,JsonResponse对象,Template模板系统
Django基础二 request request这个参数1. 封装了所有跟请求相关的数据,是一个对象 2. 目前我们学过1. request.method GET,POST ...2. reques ...
随机推荐
- 使用threejs点云秀出酷炫的图片效果(一)
来源:http://blog.csdn.net/srk19960903/article/details/70214556 使用了点云拼凑出了照片轮播十分有趣,于是用threejs实现这个效果. 首先这 ...
- Golang之beego读取配置信息,输出log模块
1,准备好配置文件 [server] listen_ip = "0.0.0.0" listen_port = [logs] log_level=debug log_path=./l ...
- sublime Text与python3的中文编码错误解决办法
在 linux服务器上运行代码报错: Python3中遇到UnicodeEncodeError: ‘ascii’ codec can’t encode characters in ordinal no ...
- mupdf编译snprintf冲突问题
mupdf-1.6-source\thirdparty\jbig2dec\config_win32.h //# define snprintf _snprintf
- 简单解决 Javascrip 浮点数计算的 Bug(.toFixed(int 小数位数))
众所周知,Javascript 在进行浮点数运算时,结果会非预期地出现一大长串小数. 解决: 如果变量 result 是计算结果,则在返回时这样写,return result.toFixed(2): ...
- thrift相关资源
官网资料,具有各语言的例子 https://thrift.apache.org/tutorial/ https://thrift.apache.org/tutorial/py
- eclipse缓存太重,新手最容易中招
有4种方法,从上到下清理:
- 人体感应模块控制LCD1602背景灯是否开启
/* Web client This sketch connects to a website (http://www.google.com) using an Arduino Wiznet Ethe ...
- js动态添加删除行,兼容ie和火狐
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- MATLAB实现截位的问题
讨论MATLAB怎样提取10进制中的位的方法,因为做FFT时要用到截位,相去验证它,向同庆请教, 原来只是除以2的N次方,取模取余就行了,可恨我还想了一下午,也没有一个好办法. 接下来的问题是,对于负 ...