app中使用afnetworking被拒怎么办

 我来答
缘Lai如茨
2016-05-27 · TA获得超过8631个赞
知道大有可为答主
回答量:7534
采纳率:92%
帮助的人:614万
展开全部
如何通过URL获取json数据
第一种,利用AFJSONRequestOperation,官方网站上给的例子:

[objc] view plain copy
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:request success:^(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解析方法:

[objc] view plain copy
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, idresponseObject) {
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获取图片
异步获取图片,通过队列实现,而且图片会有缓存,在下次请求相同的链接时,系统会自动调用缓存,而不从网上请求数据。

[objc] view plain copy
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)]; [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/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文件的内容,用的很少,这个方法在官方提供的方法里面没有

[objc] view plain copy
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, idpropertyList) {
NSLog(@"%@",error);
}];

[operation start];

如何通过URL获取XML数据
xml解析使用AFXMLRequestOperation,需要实现苹果自带的NSXMLParserDelegate委托方法,XML中有一些不需要的协议格式内容,所以就不能像json那样解析,还得实现委托。我之前有想过能否所有的XML链接用一个类处理,而且跟服务端做了沟通,结果很不方便,效果不好。XML大多标签不同,格式也不固定,所以就有问题,使用json就要方便的多。
第一步;在.h文件中加入委托NSXMLParserDelegate
第二步;在.m文件方法中加入代码

[objc] view plain copy
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文件中实现委托方法
//在文档开始的时候触发
-
[objc] view plain copy
(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操作

[objc] view plain copy
AFHTTPClient处理GET 和 POST请求.做网页的朋友们这个方法用的比较多。在要经常调用某个请求时,可以封装,节省资源。
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:responseObjectencoding:NSUTF8StringEncoding];
NSLog(@"POST请求:%@",newStr);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];

[client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation*operation, id responseObject) {
NSString* newStr = [[NSString alloc] initWithData:responseObjectencoding:NSUTF8StringEncoding];
NSLog(@"GET请求:%@",newStr);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];

运行结果:

如果需要显示网络活动指示器,可以用下面方法:

[objc] view plain copy
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

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];然后将返回的数据自己转换。
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
Storm代理
2023-07-25 广告
StormProxies是一家可靠的代理服务提供商,提供原生IP(住宅原生IP)和高匿名代理服务。以下是关于StormProxies的原生IP服务的一些信息:1. 住宅原生IP:StormProxies提供的住宅原生IP是指从真实的家庭或企... 点击进入详情页
本回答由Storm代理提供
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式