IOS开发网络数据---- AFNetworking的使用
首先得下载AFNetworking库文件,下载时得首先弄清楚,你将要开发的软件兼容的最低版本是多少。AFNetworking 2.0或者之后的版本需要xcode5.0版本并且只能为IOS6或更高的手机系统上运行,如果开发MAC程序,那么2.0版本只能在MAC OS X 10.8或者更高的版本上运行。
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 从URL获取json数据
AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestsuccess:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON) {
NSLog(@"获取到的数据为:%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {
NSLog(@"发生错误!%@",error);
}];
[operation1 start];
第二种方法,利用AFHTTPRequestOperation 先获取到字符串形式的数据,然后转换成json格式,将NSString格式的数据转换成json数据,利用IOS5自带的json解析方法:
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = operation.responseString;
NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
id dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"获取到的数据为:%@",dict);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"发生错误!%@",error);
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
如果发生Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14defc80 {NSUnderlyingError=0x14deea10 "bad URL", NSLocalizedDescription=bad URL这个错误,请检查URL编码格式。有没有进行stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
如何通过URL获取图片
异步获取图片,通过队列实现,而且图片会有缓存,在下次请求相同的链接时,系统会自动调用缓存,而不从网上请求数据。
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i./r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
[self.view addSubview:imageView];
上面的方法是官方提供的,还有一种方法,
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response,UIImage *image) {
self.backgroundImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@",error);
}];
[operation start];
如果使用第一种URLWithString: placeholderImage:会有更多的细节处理,其实实现还是通过AFImageRequestOperation处理,可以点击URLWithString: placeholderImage:方法进去看一下就一目了然了。所以我觉得还是用第一种好。
如何通过URL获取plist文件
通过url获取plist文件的内容,用的很少,这个方法在官方提供的方法里面没有
NSString *weatherUrl = @"http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";
NSURL *url = [NSURL URLWithString:[weatherUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
AFPropertyListRequestOperation *operation = [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
NSLog(@"%@",(NSDictionary *)propertyList);
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
NSLog(@"%@",error);
}];
[operation start];
如果稍不留神,可能就出现Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
"application/x-plist"
)}, got text/plain" UserInfo=0x16e91ce0 {NSLocalizedRecoverySuggestion=
...
...
, AFNetworkingOperationFailingURLRequestErrorKey= { }, NSErrorFailingURLKey=, NSLocalizedDescription=Expected content type {(
"application/x-plist"
)}, got text/plain, AFNetworkingOperationFailinponseErrorKey= { URL: } { status code: 200, headers {
"Accept-Ranges" = bytes;
Connection = "keep-alive";
"Content-Length" = 974;
"Content-Type" = "text/plain";
Date = "Sat, 25 Jan 2014 07:29:26 GMT";
Etag = ""1014c2-3ce-4ee63e1c80e00"";
"Last-Modified" = "Wed, 25 Dec 2013 23:04:24 GMT";
Server = "nginx/1.4.2";
} }}
可能还会出现乱码,解决办法就是[AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
如何通过URL获取XML数据
xml解析使用AFXMLRequestOperation,需要实现苹果自带的NSXMLParserDelegate委托方法,XML中有一些不需要的协议格式内容,所以就不能像json那样解析,还得实现委托。我之前有想过能否所有的XML链接用一个类处理,而且跟服务端做了沟通,结果很不方便,效果不好。XML大多标签不同,格式也不固定,所以就有问题,使用json就要方便的多。
第一步;在.h文件中加入委托NSXMLParserDelegate
第二步;在.m文件方法中加入代码
NSURL *url = [NSURL URLWithString:@"http://113.106.90.22:5244/sshopinfo"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request,NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser*XMLParser) {
NSLog(@"%@",error);
}];
[operation start];
第三步;在.m文件中实现委托方法
//在文档开始的时候触发
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(@"解析开始!");
}
//解析起始标记
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(@"标记:%@",elementName);
}
//解析文本节点
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"值:%@",string);
}
//解析结束标记
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString *)qName{
NSLog(@"结束标记:%@",elementName);
}
//文档结束时触发
-(void) parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@"解析结束!");
}
运行的结果:
如何使用AFHTTPClient进行web service操作
BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"text/html"];
[client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject) {
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"POST请求:%@",newStr);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
[client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, idresponseObject) {
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"GET请求:%@",newStr);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
运行结果:
Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x16774de0 {NSErrorFailingURLKey=http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1, AFNetworkingOperationFailinponseErrorKey= { URL: http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1 } { status code: 200, headers {
XXX
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
返回数据格式不对。注销这句话: op.responseSerializer = [AFJSONResponseSerializerserializer];然后将返回的数据自己转换。
error = Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x1740f2c00 {com.alamofire.serialization.response.error.response= { URL: http://192.168.5.132/api/cats?type=apps } { status code: 200, headers {
Connection = "keep-alive";
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 05 Nov 2015 10:27:42 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
} }
AF可以接受json以外的数据 自己随意定义的格式都可以 只不过要使用AFNetwork提供的解析方法的话 它只对通用的格式做处理 你返回的数据不是那种格式 他就无法解析出来 那要你自己处理 改变AFNetWork的库文件 找到他判断错误的那个函数 让他从正确的方法返回 如果你不会的话 就在返回错误的方法处理也可以 反正数据已经到了 网络的目的 是为了得到数据 你的数据已经到了 只不过AFNetwork认定你的数据不符合常用的格式 确实也不符合 因为你的数据是加密的东西 而且是对整个json格式加密 而不是只对值加密 所以要实现这种格式的传输 只能修改AFNetwork的库 而你不会 那就先这么用着
举个例子 你们现在的做法是对整个字符串加密 如果你不这么做 只将值部分加密 而不对键加密 就是{“message”:“值的密文”} 那么这个数据仍然符合json格式 AFNetwork依然能解析出来 你们对整个json字符串都加密了 那密文就不是json格式了 所以你们可以按我说的改 仅加密值部分 也就按照现在的方法 在错误的返回方法里面处理数据 但是你自己知道数据是正确的 只不过AFNetwork误判了而已 这个属于原理上东西 改不了 要么就是不让AFNetwork解析 他只透传 你自己解析 如果让他帮你解析 你就要指定一个格式给他 指定了格式 而你的数据不符合格式 那就是按错误的方法返回
AFNetworking关于HTTP认证的问题
AFNetwork实现basic认证的方法很简单
http://stackoverflow.com/questions/12440059/using-afnetworking-and-http-basic-authentication
创建一个NSURLCredential对象,然后将对象赋值到请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:@"Username" password:@"Password" persistence:NSURLCredentialPersistenceForSession]; [manager setCredential:credential];
IOS开发网络数据---- AFNetworking的使用的更多相关文章
- iOS开发网络数据之AFNetworking使用
iOS开发网络数据之AFNetworking使用 如何选择AFNetworking版本 首先得下载AFNetworking库文件,下载时得首先弄清楚,你将要开发的软件兼容的最低版本是多少.AFNetw ...
- iOS开发网络数据之AFNetworking使用1
链接地址:http://blog.csdn.net/daiyelang/article/details/38421341 如何选择AFNetworking版本 官网下载2.5版本:http://afn ...
- iOS开发网络数据之AFNetworking使用 分类: ios技术 2015-04-03 16:35 105人阅读 评论(0) 收藏
http网络库是集XML解析,Json解析,网络图片下载,plist解析,数据流请求操作,上传,下载,缓存等网络众多功能于一身的强大的类库.最新版本支持session,xctool单元测试.网络获取数 ...
- iOS开发网络篇—数据缓存
iOS开发网络篇—数据缓存 一.关于同一个URL的多次请求 有时候,对同一个URL请求多次,返回的数据可能都是一样的,比如服务器上的某张图片,无论下载多少次,返回的数据都是一样的. 上面的情况会造 ...
- iOS开发网络篇—发送json数据给服务器以及多值参数
iOS开发网络篇—发送json数据给服务器以及多值参数 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 (2)设置请求头 (3)设置JSON数据为请求体 ...
- iOS开发网络篇—JSON数据的解析
iOS开发网络篇—JSON数据的解析 iOS开发网络篇—JSON介绍 一.什么是JSON JSON是一种轻量级的数据格式,一般用于数据交互 服务器返回给客户端的数据,一般都是JSON格式或者XML格式 ...
- iOS开发网络篇—XML数据的解析
iOS开发网络篇—XML数据的解析 iOS开发网络篇—XML介绍 一.XML简单介绍 XML:全称是Extensible Markup Language,译作“可扩展标记语言” 跟JSON一样,也是 ...
- iOS开发网络篇—HTTP协议
iOS开发网络篇—HTTP协议 说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) ...
- 02.iOS开发网络篇—HTTP协议
iOS开发网络篇—HTTP协议 说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) ...
随机推荐
- 如何将两个json合并成一个
//调用方法: var targetObject = [{name:"11",age:11}]; var sourceObject = [{name:"22", ...
- AWS-CDH5.5安装 CM配置节点
在CM节点上进行安装时出现错误: ================================================================================ Pa ...
- LINUX centos 忘记密码
entos7采用的是grub2,和centos6.x进入单用户的方法不同.但是因为用的是真机环境无法截图,所以只是大概描述以下思路. init方法 1.centos7的grub2界面会有两个入口,正常 ...
- [小菜随笔]关于monkey报错日志分析
今天小菜在一个测试群内看到群友发出一个monkey的报错信息,其实是一个很简单的报错 个人觉得monkey虽然操作起来比较简易,但其实查看日志分析日志也是很重要的环节,如果对错误分析不够详细,就容易误 ...
- Multiple View Geometry in Computer vision 1.1节部分翻译
1.1简介—无处不在的投影几何 我们都熟悉射影变换.当我们看一幅图,我们看到的方形不是方形,或圆形不是圆形.平面立体映射到图片上的变换是一个投影变换的例子. 因此投影变换时保留的几何属性是什么呢?当然 ...
- js控制select下拉列表数据绑定
JS代码部分: <script type="text/javascript"> $(document).ready(function () { $("sel ...
- Android Bitmap Drawable 常用摘要
1.缩放 public Bitmap scalingBitmap(Bitmap bitmap, int newW, int newH) { int w = bitmap.getWidth(); int ...
- suspend
两个线程的run方法同时调用一个加了同步锁的方法,如果一个线程使用了suspend方法,那么会独占并且锁死这个同步方法,别的线程就永远没有办法进入这个线程了. 特别的是,在main方法中,调用一个线程 ...
- ajax绑定
function Select() { var data = $("#SelectByTime").serialize(); $.post( "settle.aspx?a ...
- C#在数据层过滤属性中的主键
C#使用泛型+反射做为数据层时,一个很都头疼的问题,如何让C#属性在程序里识别出哪个属性是主键,在拼接SQL时,不能把主键拼接到SQL语句里. 这个需要自定义一个属性.新建一个类文件,命名为Prosp ...